/*
 *  AJAX:
 *  /fanzone/player/{matchId}/{playerId}/{userId}/{playerRating}/{position}/{clubId}.json
 * 
 */

$.ui.fanzone.subclass('ui.fanzonefanrating', {
    klass: '$.ui.fanzonefanrating',
    options: {
        selects:		'select', // {String}	required identifier for input submission method
        rows:			'tr' 	  // {String}	required identifier containing submission data
    },
    create: function() {

    },
    _init: function() {
    	this.el.rows	= this.element.find(this.options.rows);
    	this.el.selects	= this.element.find(this.options.selects);
    	this.el.login	= this.element.find('#fanzonefan-login');
        this.el.submits	= this.element.find('input[type=submit]');
        
        this.addEvents();
        this.el.submits.hide();
    },
    addEvents: function() {
    	if (this.data.loggedin) {
    		this.el.login.remove();
    		this.el.selects.bind("change", $.proxy(this.voteOnChange, this));
    	} else {
    		this.el.selects.attr('disabled', 'disabled');
    	}
    },
    voteOnChange: function( event ) {
    	var self    = this;
        var select  = $(event.target).closest(this.el.selects);
        var row     = $(event.target).closest(this.el.rows);

       	// Add player data to ajax string
        var data = this.options.ajax;
        	data = data.replace('{userId}', 	  this.data.userId	);	//{userId}
        	data = data.replace('{playerId}',	  row.attr('pid')		);	//{playerId}
        	data = data.replace('{playerRating}', select.val()			);	//{playerRating}
        	data = data.replace('{position}', 	  row.attr('position') 	);	//{position}
        	data = data.replace('{clubId}', 	  row.attr('club')		);	//{club}
        	data = data.replace(' ', '+');	// replace Goal Keeper space
        	
        // If a valid rating, Submit Form, Retrieve receipt, call render()
        if (select.val() != "-1") {
	        $.ajax({
			    type: "GET",
			    url: data,
			    cache: false,
			    dataType: "json",
			    beforeSend: function( xhr ) {
			    },
			    success: function( json, xhr, status ) {
			        self.render( json, row );
			    },
			    error: $.proxy(function( xhr, status, error ) {
			    	self.renderError( xhr.status, row );
	            },this) 
			});
        }
    },
    render: function( json, target ) {
    	
    	if (!json.exception && !json.error) {
    		
    		var yourRating 		= json.fanZonePlayerRatingReceipt.yourRating;
    		var matchAvg   		= json.fanZonePlayerRatingReceipt.matchAverage;
    		var seasonalAverage = json.fanZonePlayerRatingReceipt.seasonalAverage;
    		
    		// Return values into right hand columns
    		target.find('.match' ).hide().text( matchAvg 		).fadeIn();
    		target.find('.season').hide().text( seasonalAverage ).fadeIn();

        } else {
            // Error Text !!! Should not reach this point
            target.empty().html('<td colspan="4"><p class="data-error">There was a server error submitting your rating</p></td>');
        }
    },
    renderError: function( status, target ) {
    	// Hide target to render error
    	target.hide().empty();
    	switch ( status ) {
    	case 404:
    		target.html('<td colspan="4"><p class="data-error">There was a server error submitting your rating</p><!--404--></td>');
    		break;
    	case 403:
    		target.html('<td colspan="4"><p class="data-error">Error submitting your rating: No submissions allowed</p><!--403--></td>');
    		break;
    	default:
    		target.html('<td colspan="4"><p class="data-error">There was a server error submitting your rating</p></td>');
    	}
    	// Re-render target
    	target.fadeIn();
    }
});
/**
 *
 *  AJAX:
 *  Fanzone Page: Match Rating
 *  /ajax/fanzone/match/{matchId}/{userId}/{matchRating}/{supportedClubId}.json
 * 
 */

$.ui.fanzone.subclass('ui.matchrating', {
    klass: '$.ui.matchrating',
    options: {
        cancel: 		'Clear Rating',	// {String}		  advisory title for the 'cancel' link
		cancelValue: 	'',				// {Value}		  value to submit when user click the 'cancel' link
		split: 			0				// {Integer}	  split the star into how many parts?
    },
    create: function() {

    },
    _init: function() {
    	this.el.inputs   = this.element.find('input');
    	this.el.stars    = this.element.find('#rating-stars .star');
    	this.el.target   = this.element.find('#fanzonematchrating-results');
    	
    	this.el.submit   = this.el.inputs.filter('[type=submit]');
    	this.el.rating   = this.el.inputs.filter('[name=matchrating]');
    	
    	this.ratingvalue = null;
    	
    	this.addRating(); // Apply rating JScript
    	if (this.options.ajax) {
    		this.el.legend.hide();
    		this.addClubInfo();	//_super()
	    	this.el.target.hide();
	    	this.addEvents();
    	}
    },
    addRating: function () {
    	
    	// Set options for exlib
    	$.fn.rating.options.cancel 		= this.options.cancel;
    	$.fn.rating.options.cancelValue = this.options.cancelValue;
    	$.fn.rating.options.split		= this.options.split;
    	
    	// Use external /exlibs/js/jquery.rating.js
    	this.element.find('#rating-stars .star').rating();
    },
    addEvents: function () {
    	// Show either 'login' or 'submit' buttons 
		if ( this.data.loggedin ) {
			this.element.find( '#fanzonematch-login'  ).remove();
			this.element.find( '#fanzonematch-submit' ).fadeIn();
		} else {
			this.el.stars.rating('readOnly',true);
			this.element.find( '#fanzonematch-submit' ).remove();
			this.element.find( '#fanzonematch-login'  ).fadeIn();
		}
    	
		this.el.submit.bind('click', $.proxy( function() {
			var self		 = this;
			var ajax   		 = this.options.ajax;
			this.ratingvalue = this.el.inputs.filter('[name=matchrating]:checked').val();
			
			if (this.ratingvalue > 0 && this.ratingvalue < 6) {
				// Remove submit button
				this.el.submit.fadeOut();
				// Disable inputs
	            this.el.stars.rating('readOnly',true);
				// Submit Form, Retrieve receipt, Render result 
				var data = ajax;
					data = data.replace('{matchRating}', this.ratingvalue);
					data = data.replace('{userId}', 	 this.data.userId);
					data = data.replace('{userClubId}',  this.data.teamId);

				$.ajax({
					type: "GET",
	                url:  data,
	                cache: false,
	                dataType: "json",
	                beforeSend: function( xhr ) {
	                },
	                success: function( json, xhr, status ) {
	                	self.render( json );
	                },
	                error: function( xhr, status, error ) {
	                	self.renderError( xhr.status, error );
	                }
				});
			}
			//cancel the submit button default behaviours
			return false;
    	}, this));
    },
    render: function( json ) {    	
    	// Target <div id="fanzonematchrating-results"> element
    	if (!json.exception && json.fanZoneMatchRatingReceipt) {

        	// Set floating span for yourAnswer == X.answer
            var spanBox = '<span class="yourAnswer" style="background:'+this.options.yourcolor+'"></span>';
        	
        	// Receipt Data
        	var home 			   = {}; 
        	var away 			   = {}; 
        	var neutral 		   = {};
            var yourRating		   = this.ratingvalue;												// 2	//json.fanZoneMatchRatingReceipt.yourRating;
            	home.rating		   = json.fanZoneMatchRatingReceipt.homeFansModeRating; 			// 2
            	home.percentage	   = json.fanZoneMatchRatingReceipt.percentageHomeFansModeRating; 	// 33
            	neutral.rating 	   = json.fanZoneMatchRatingReceipt.neutralFansModeRating; 			// 3
            	neutral.percentage = json.fanZoneMatchRatingReceipt.percentageNeutralFansModeRating;// 42
            	away.rating		   = json.fanZoneMatchRatingReceipt.awayFansModeRating; 			// 5
            	away.percentage	   = json.fanZoneMatchRatingReceipt.percentageAwayFansModeRating; 	// 65

        	// Target Table Cells
        	var homeTarget		= $('.home    .result' 	+ home.rating, 	  this.el.target);
        	var awayTarget		= $('.away    .result' 	+ away.rating,    this.el.target);
        	var neutralTarget	= $('.neutral .result' 	+ neutral.rating, this.el.target);
        	var yourTarget		= $('.'+this.options.fanGroup+' .result' + yourRating , this.el.target);

            homeTarget.css({'background' : this.options.homecolor})
            		  .html(home.percentage    + "%");
            awayTarget.css({'background' : this.options.awaycolor})
            		  .html(away.percentage    + "%");
            neutralTarget.css({'background' : this.options.neutralcolor})
            		  .html(neutral.percentage + "%");
            
            // Set yourAnswer
            switch ( this.data.teamId ) {
                case this.options.homeId:
                	if ( home.rating == yourRating) {
                		homeTarget.html(spanBox+home.percentage+"%");
                	} else {
                		yourTarget.css({'background' : this.options.yourcolor});
                	}
                	break;
                case this.options.awayId:
                	if ( away.rating == yourRating) {
                		awayTarget.html(spanBox+away.percentage+"%");
                	} else {
                		yourTarget.css({'background' : this.options.yourcolor});
                	}
                	break;
                default: //neutral
                	if ( neutral.rating == yourRating) {
                		neutralTarget.html(spanBox+neutral.percentage+"%");
                	} else {
                		yourTarget.css({'background' : this.options.yourcolor});
                	}
                	break;
            }                
            
            // Move to after options and slideDown
            this.el.target.slideDown();
            
            // Swap club logo out for legend
            this.el.faveClub.fadeOut();
            this.el.legend.fadeIn();
        }
    },
    renderError: function( json, status ) {
    	this.el.target.empty();

    	switch ( status ) {
    	case 404:
    		this.el.target.html('<p class="data-error">There was an error submitting your rating:<br/>Not found</p><!--'+status+'-->');
    		break;
    	case 400:
    		this.el.target.html('<p class="data-error">There was an error submitting your rating:<br/>Please try again later</p><!--'+status+'-->');
    		break;
    	case 403:
    		this.el.target.html('<p class="data-error">There was an error submitting your rating:<br/>No submissions allowed</p><!--'+status+'-->');
    		break;
    	case 409:
    		this.el.target.html('<p class="data-error">There was an error submitting your rating:<br/>You have already rated this match</p><!--'+status+'-->');
    		break;
    	case 401:
    		this.el.target.html('<p class="data-error">There was an error submitting your rating:<br/>Unauthorised. Please log in.</p><!--'+status+'-->');
    		break;
    	case 500:
    		this.el.target.html('<p class="data-error">There was a server error submitting your rating</p><!--'+status+'-->');
    		break;
    	default:
    		this.el.target.html('<p class="data-error">There was a server error submitting your rating</p><!--'+status+'-->');
    	}
    	// Re-render target
    	this.el.target.slideDown();
    }
});
$.ui.widget.subclass('ui.fixturechange', {
    klass: '$.ui.fixturechange',
    options: {

    },
    // Called from constructor before _init() – automatically calls this._super() before function
   _create: function() { 
        this.options.hash = {};
        this.options = $.getAttributeHash( this.element, this.options );
    },
    // Called from constructor after _create() – automatically calls this._super() before function
    _init: function() {
        this.doToast();
    },
    doToast: function (arg) {

	    $('img#closechangeinfo').click(function() {
          $('.fixtureheader .changeinfo').slideToggle('slow');
        });
    	
    }
    
});
$.ui.basewidget.subclass('ui.fixtureheader', {
    klass: '$.ui.fixtureheader',
    options: {
        eventManager:   null,                   // {EventManager}   reference to js/libs/EventManager.js, passed in via init.js
        hash:           null,                   // {Hash}           define objects and arrays within the constructor, else it will create a class variable
        state:          null,                   // {String}         State of the fixture to determine countdown/polling/do nothing
        prestate:       null,                   // {String}         PRE_MATCH state before and after team sheets are available (swap in flash)
        matchId:        null,                   // {Number}         PAId for the given match
        ajax:           null,                   // {String}         url to poll for updates to fixture info
        interval:       10000,                  // {Number}         interval in ms for poller to retrieve json
        counterOutput:  null,                   // {Number}         Countdown end point
        expiryText:     'Waiting for kick-off', // {String}         Text to display between 0 and LIVE data
        timezone:       0,
        labels:         ['yrs','mths','wks','days','hrs','mins','secs']
    },
    required: {
        state:          String,
        prestate:       String,
        ajax:           String,
        counterOutput:  Number,
        matchId:        Number
    },
   _create: function() { 
        this.options.hash = {};
        this.options = $.getAttributeHash( this.element, this.options );
        
        this.el.countdown  = this.element.find('#fixtureCounter');
        this.el.score      = this.element.find('#fixtureScore');
        this.el.scorespans = this.element.find('#fixtureScore span');
        this.el.goalspans  = this.element.find('.goals');
        this.el.logoview   = this.element.find('.logoview');
        this.el.flashview  = this.element.find('.flashview');
        this.el.calendar   = this.element.find('.calendar');
        this.el.tickets    = this.element.find('.tickets');
        //DataCache.register( this.options.ajaxBroadcaster, this.renderBroadcasters );
    },
    _init: function() {
    	if ( this.options.state === "LIVE" ) {
    		this.el.countdown.fadeOut().remove();
    		this.el.score.show();
        	this.registerAjaxPoller( this.options.ajax );
        }
    	else if ( this.options.state === "POST_MATCH") {
    		this.el.countdown.remove();
    		this.el.score.show();
    	} 
    	else if ( this.options.state === "PRE_MATCH") {
        	this.addCountdown();
        	// register an event in PRE_LIVE when next for both teams
        	// to register state change
        	if (this.options.prestate != "NOT_NEXT_FIXTURE_FOR_BOTH_TEAMS") {
        		this.registerAjaxPoller( this.options.ajax );
        	}
        }    	
    	//this.lookupItems();
        this.addTracking();
        //DataCache.lazyLoad( this.options.ajaxBroadcaster, this.renderBroadcasters );
    },
    destroy: function() {
        this.unregisterAjaxPoller();
        this.removeTracking();
        this._super();
    },
    registerAjaxPoller: function( url ) {
        AjaxPoller.register({
            url:          url,
            type:         "GET",
            interval:     this.options.interval, // TODO: Reconfigure for live
            dataType:     "json",
            handler:      [this, this.ajaxPollHandler],
            eventManager: this.eventManager
        });
    },
    unregisterAjaxPoller: function() {
        AjaxPoller.unregister({
            handler:      [this, this.ajaxPollHandler]
        });
    },
    //***** Ajax Command *****//
    ajaxPollHandler: function( json, status, xhr ) {
    	
    	if ( json.matchHeaderSection && json.matchViewContext.matchId === this.options.matchId ) {

    		//PRE_MATCH : No team sheets (logoview) to team sheets (flashview)
    		if (json.matchHeaderSection.matchState.stateVariation === "NEXT_FIXTURE_FOR_BOTH_TEAMS_WITH_TEAM_SHEETS" &&
    				this.options.prestate === "NEXT_FIXTURE_BUT_NO_TEAM_SHEETS") {
    			// Swap in flash for logos
    			this.el.logoview.fadeOut();
    			this.el.flashview.fadeIn();
    			// Disable calendar link
    			if ( this.el.calendar.hasClass('enabled') ) {
    				this.el.calendar.fadeOut();
    				var calLink = this.el.calendar.find('a');
	    			calLink.parent().text( calLink.text() );
	    			calLink.remove();
	    			this.el.calendar
	    				.removeClass( 'enabled' )
	    				.addClass( 'disabled' );
	    			this.el.calendar.fadeIn();
    			}
    			// Disable tickets link
    			if ( this.el.tickets.hasClass('enabled') ) {
    				this.el.tickets.fadeOut();
    				this.el.tickets
    					.removeClass( 'enabled' )
    					.addClass( 'disabled' );
    				this.el.tickets.html('<span>Tickets</span> All ticket options');
    				this.el.tickets.fadeIn();
    			}
    		}
    		//PRE_MATCH to LIVE
    		else if (json.matchHeaderSection.matchState.matchState === "LIVE" && 
    				this.options.state === "PRE_MATCH") {
    			this.el.countdown.fadeOut().remove();
        		this.el.score.show();
        		this.options.state = "LIVE";	// Switch state to LIVE
    		}
    		//LIVE
    		else if (json.matchHeaderSection.matchState.matchState === "LIVE" && 
    				this.options.state === "LIVE") {
	    		// Redraw Score and Scorers
	        	var jsonHash = json.matchHeaderSection.matchDetails || {};
	            this.updateHeader( jsonHash );
    		}
    		else {
    			// Not ready... so nothing to do. Keep on waiting on.
    		}
        } else {
            console.warn(this.klass,':ajaxLoadHeader(json,status,xhr) - matchId (', this.options.matchId,') does not match headerData: ', json.matchViewContext.matchId, ' in jsonHash: ', json);
        }
        //this._init();
    },

    //***** Data Services *****//
    updateHeader: function( json ) {
        try {
            if ( json.finalScore ) {
                var homeNewScore = json.finalScore.home;
                var awayNewScore = json.finalScore.away;
                var scorerList   = ""; 
                
                // VERY DEPENDANT ON MARKUP
                var homeScoreTarget  = this.el.scorespans.closest('.homeScore');
                var awayScoreTarget  = this.el.scorespans.closest('.awayScore');
                var homeScorerTarget = this.el.goalspans.closest('.home');
                var awayScorerTarget = this.el.goalspans.closest('.away');

                // Update if Score has changed
                if ( homeScoreTarget.text() != homeNewScore ) {
                    // Update the score in the main header section
                    homeScoreTarget.hide().text( homeNewScore ).fadeIn();
                    // Update the scorer list on the sides
                    scorerList = this.updateScorers( json.homeTeamScorers );
                    homeScorerTarget.hide().empty().html( scorerList ).fadeIn();
                }
                if ( awayScoreTarget.text() != awayNewScore ) {
                    // Update the score in the main header section
                    awayScoreTarget.hide().text( awayNewScore ).fadeIn();
                    // Update the scorer list on the sides
                    scorerList = this.updateScorers( json.awayTeamScorers );
                    awayScorerTarget.hide().empty().html( scorerList ).fadeIn();
                }
                
                /**
                 * this section of code targets the score above the match
                 * statistics bars on the 'STATISTICS' tab. Thus the target
                 * must be accessed via the page window and is not within 
                 * the DOM element the widget is applied to.
                 *
                 * This is done within the fixture header code to ensure the
                 * update takes place at the same time.
                 *
                 * TODO: Refactor the any match AJAX polling code to a single
                 *       poller.
                 */
                // VERY DEPENDANT ON MARKUP && TAB; BASICALLY ASYNCRONOUS
                var statsScoreTarget  = $('.matchstatistics .header .score');
                var statsScoreNewText = homeNewScore + ' - ' + awayNewScore;
                if ( statsScoreTarget.length && statsScoreTarget.text() != statsScoreNewText ) {
                    statsScoreTarget.hide().text( statsScoreNewText ).fadeIn();    
                }
            }
        } catch(e) {
            console.log('EXCEPTION: ', this&&this.klass||'' ,' updateHeader: function(', json, ') ',  e);
            console.dir(e);
        }
    },
    updateScorers: function( json ) {
    	var scorerAry = json || [];
    	var html = "";

    	try {
	    	if ( scorerAry != [] ) {
	    		html += '<ul>';
	    		for (var i=0, n=scorerAry.length; i<n; i++) {
	    			var player   = scorerAry[i].player.fullName;
	    			var goalList = this.formatScorerList( scorerAry[i].goals );
	    			html += '<li>';
	    			html += player;
	    			html += goalList;
	    			html += '</li>';
	    		}
	    		html += '</ul>';
	    	}
    	} catch(e) {
            console.log('EXCEPTION: ', this&&this.klass||'' ,' updateScorers: function(', json, ') ',  e);
            console.dir(e);
        }
        return html;
    },
    formatScorerList: function( array ) {
    	var html = "";
    	try {
    		if (array instanceof Array ) {
    			html += ' (';
    			for (var i=0, n=array.length; i<n; i++) {
    				var goalTime = array[i].time;
    				var goalType = array[i].type;
    				
    				if (i>0) {
    					html += ', ';
                    }
                    
                    html += goalTime;
                    switch (goalType) {
                        case("OWN_GOAL"): html += ' OG';  break;
                        case("PENALTY"):  html += ' Pen'; break;
                        default: //add nothing
                    }
                }
                html += ')';
            }
        } catch(e) {
            console.log('EXCEPTION: ', this&&this.klass||'' ,' formatScorerList: function(', array, ') ',  e);
            console.dir(e);
        }
        return html;
    },
    //***** Counter for Pre-Match State *****//
    addCountdown: function() {
    	//http://keith-wood.name/countdown.html
    	this.el.countdown.countdown({
	        until: 	  	new Date(this.options.counterOutput),
	        layout:   	'<p class="timer">{dnn} {sep} {hnn} {sep} {mnn} {sep} {snn}</p><p><span>{dl}</span><span>{hl}</span><span> {ml}</span><span>{sl}</span>',
	        labels:   	this.options.labels,
	        labels1:  	this.options.labels,
	        timezone:	this.options.timezone,
	        expiryText: this.options.expiryText
	    });
    	this.el.countdown.fadeIn();
    },
    addTracking: function () {
        
        var $h = $('.fixtureheader','#body');
        
        var teamInfo = 
            $('.teaminfo .home',$h).text().toLowerCase().replace(" ","-")
            + "-vs-" +
            $('.teaminfo .away',$h).text().toLowerCase().replace(" ","-"); 
        
        $('.broadcastinfo .calendar.enabled a',$h).live("click",function(){
            window.YWABeacon.trigger("YWAEvent:track",["cf",19,teamInfo])
                     .trigger("YWAEvent:track",["action","06"])
                     .trigger("YWAEvent:track",["submit"]);
        });
        
        $('.broadcastinfo .tickets.enabled a',$h).live("click",function(){
            window.YWABeacon.trigger("YWAEvent:track",["cf",18,teamInfo])
                     .trigger("YWAEvent:track",["action","04"])
                     .trigger("YWAEvent:track",["submit"]);
        });
        
    },
    removeTracking: function () {
        
    }
    
});
$.ui.basewidget.subclass('ui.previousEncounters', {
    klass: "$.ui.previousEncounters",
    options: {
        opts:               'select',
        target:             '.stats-data',
        submit:             'input[type=submit]',
        spinnerSelector:	'.spinner',
        ajax:               null,
        homelogo:           null,
        awaylogo:           null,
        playersurl:			null,
        clubsurl:			null
    },
    required: {
        opts:               String,
        target:             String,
        ajax:               String,
        homelogo:           String,
        awaylogo:           String
    },
    _create: function() {
        this.el.opts      = this.element.find(this.options.opts);
        this.el.target    = this.element.find(this.options.target);
        this.el.submitBtn = this.element.find(this.options.submit);
        this.el.templates = $("script[type='text/x-jquery-tmpl']");
        this.el.logo      = {
                			home: this.options.homelogo,
                			away: this.options.awaylogo
        };
        this.playersurl	  = this.options.playersurl;
        this.clubsurl	  = this.options.clubsurl;
        this.errMsg 	  = "Error Retrieving Data";
    },
    _init: function() {
        this.el.opts.live('change', $.proxy(this.onSelect, this));
        this.el.submitBtn.hide();
        this.el.opts.change();
    },
    renderError: function() {
    	this.el.target.empty();
    	this.el.target.html('<p class="data-error">'+this.errMsg+'</p>');
    	this.el.target.fadeIn();
    },
    hide: function( json, target, index, template ) {
        var renderIn = $(target).fadeOut().empty();
    },
    onSelect: function( event ) {
        
        var self      		 = this;
        var ajax      		 = this.options.ajax;
        var spinnerTemplates = this.el.templates.filter(this.options.spinnerSelector);
        var staticTemplates  = this.el.templates.filter('[static]');
        var ajaxTemplate     = this.el.templates.filter('.previous-stats');

        var counter = ++$.ui.previousEncounters.counter; // Semaphore to prevent multiple loading
        if (ajax) {
        	
        	spinnerTemplates.each( $.proxy(this.render, this, {}, this.el.target) ); // template passed as third param
        	var data = ajax;
				data = data.replace('{pHowMany}', this.el.opts[0].value);
				data = data.replace('{pAtWhich}', this.el.opts[1].value);
        	
	        $.ajax({
	            type: "GET",
	            url:  data,
	            cache: false,
                dataType: "json",
	            beforeSend: function( xhr ) {
	        	},
	            success: function( json, xhr, status ) {
	                if ( counter != $.ui.previousEncounters.counter ) { return; }
	                ajaxTemplate.each( $.proxy(self.render, self, json, self.el.target) ); // template passed as third param
	            },
	            error: function( xhr, status ) {
	            	this.renderError();
	            }
	        });
        }
    },
    render: function( json, target, index, template ) {
    	if (json.matchPastMeetingsSection && json.matchPastMeetingsSection.pastMeetingDetailedStatistics) {
	        json.logo 		= this.el.logo; // add logos to data for template
	        json.playersurl = this.playersurl;
	        json.clubsurl 	= this.clubsurl;
	        json.labels		= {home: "home", away: "away"};
	        
	        //console.log('json',json);
	        var renderIn = $(target).hide().emptyGC();
	        var rendered = $(template).tmpl(json).appendTo( renderIn );
	        
	        $.initWidgets( rendered );
	        renderIn.data("widget")._init();
	        target.show();

    	} else {
	        var renderIn = $(target).hide().empty();
	        var rendered = $(template).tmpl(json).appendTo( renderIn );
	        target.show();
    	}
    }
});
$.ui.previousEncounters.counter = 0;
$.ui.widget.subclass('ui.previousmatchstats', {
    klass: '$.ui.previousmatchstats',
    options: {
        eventManager: null,    // {EventManager} reference to js/libs/EventManager.js, passed in via init.js
        hash:         null     // {Hash}         define objects and arrays within the constructor, else it will create a class variable
    },

    // Called from constructor before _init() – automatically calls this._super() before function
   _create: function() { 
        this.options.hash = {};
        this.options = $.getAttributeHash( this.element, this.options );
    },

    // Called from constructor after _create() – automatically calls this._super() before function
   _init: function() {
        this.addTabs();
        this.addEvents();
        
        this.element.find('li:first').click();
    },
    addTabs: function () {
    	/**
    	 * Could be better implemented using jQuery Tabs...
    	 * 
    	 * <ul class="statstabs ea">
	     * 	   <li id="Goals" class="selected">Goals</li>
	     * 	   <li id="Time">Time of Goals</li>
	     * 	   <li id="Position">Goals by Pitch Position</li>
	     * 	   <li id="Scorers">Goal Scorers</li>
	     * </ul>
    	 */
    	var li1 = $.el("li").addClass('Goals selected').text("Goals"),
    		li2 = $.el("li").addClass('Time').text("Time of Goals"),
    		li3 = $.el("li").addClass('Position').text("Goals by Pitch Position"),
    		li4 = $.el("li").addClass('Scorers').text("Goal Scorers"),
    		ul  = $.el("ul").addClass('statstabs ea').append(li1).append(li2).append(li3).append(li4).prependTo(this.element)
    		// added the created elements to the DOM with prependTo()
    },
    addEvents: function () {
    	
    	var self = this;
    	this.tabs = this.element.find('li');

    	this.tabs.live('click', function() {
    		// @context now within clicked tab 
    		self.tabs.removeClass('selected');
    		
    		var showId = 'wrapper' + $(this).attr('class'); // eg wrapperTime
    		
    		self.element.find('.wrapper:not(#'+showId+')').hide();
    		self.element.find('.wrapper#'+showId).show();

    		$(this).addClass('selected');
    	});
    	
    }   
});
$.ui.widget.subclass('ui.videoModal', {
    klass: '$.ui.videoModal',
    options: {
        eventManager: null,    // {EventManager} reference to js/libs/EventManager.js, passed in via init.js
        hash:         null,    // {Hash}         define objects and arrays within the constructor, else it will create a class variable
        dimensions:   "",      // {String}       
        srcflv:       "",      // {String}
        player:       ""
    },

    // Called from constructor before _init() – automatically calls this._super() before function
   _create: function() { 
        this.options.hash = {};
        this.options = $.getAttributeHash( this.element, this.options );
    },

    // Called from constructor after _create() – automatically calls this._super() before function
   _init: function() {
    	this.addDOM();
    	this.addEvents();
    },
    
    addDOM: function() {
    	// only init the modal HTML if it's not already been done!
    	if ($('#videoModal').length < 1) {
    		var container = $.el('div').attr('id','videoModal'),
    		    ovr = $.el('div').addClass('overlay'),
    		    cls = $.el('div').addClass('close'),
    		    flv = $.el('div').addClass('video');
    		    
    		$('body').append(
    			container.append(ovr)
    				.append(cls)
    				.append(flv)
    		);
    		return true;
    	} else {
    		return false;
    	}
    	
    },
    
    show: function(){
    	this.drawSWF();
    	var docW = $(window).width(),
    	    docH = $(window).height(),
    	    dims = this.options.dimensions.split(',')
    	    vidW = dims[0],
    	    vidH = dims[1],
    	    vidTop = (docH/2 - vidH/2)+'px',
    	    vidLeft = (docW/2 - vidW/2)+'px',
    	    cloTop = (docH/2 - vidH/2 - 21) + 'px';
    	    cloLeft = (docW/2 + (vidW/2) - 21)+'px',
    	
    	console.log('docH',docH,
    				'\ndocW',docW,
    				'\ndims',dims,
    				'\nvidW',vidW,
    				'\nvidH',vidH,
    				'\nvidTop',vidTop,
    				'\ncloLeft',cloLeft);
    	    
    	$('.video','#videoModal').css({
    		'top':vidTop,
    		'left':vidLeft
    	});
    	
    	$('.close','#videoModal').css({
    		'top':cloTop,
    		'left':cloLeft
    	});
    	
    	$('#videoModal').fadeIn('fast');
    },
    
    hide: function(){
    	$('#videoModal').fadeOut('fast');
    },
    
    drawSWF: function(){
    	
    	$('.video','#videoModal').html($.el('div').attr('id','videomodalfeature'));
    	
    	var dims = this.options.dimensions.split(',');
    	
    	var swfVersionStr = "0";       
        var xiSwfUrlStr = "";
        var flashvars = {   
        	                src:this.options.srcflv,
                            autostart: 'true',
                            includeads: 'false'
                        };
        var params = {};
        params.quality           = "high";
        params.bgcolor           = "#000000";
        params.play              = "true";
        params.loop              = "true";
        //params.wmode = "window";
        params.scale             = "showall";
        params.menu              = "true";
        params.devicefont        = "false";
        params.salign            = "";
        params.allowscriptaccess = "sameDomain";
        params.allowFullScreen   = "true";
        params.wmode             = "transparent";
        var attributes = {};
        attributes.id            = "AkamaiPlayer";
        attributes.name          = "AkamaiPlayer";
        attributes.align         = "middle"; 
        swfobject.embedSWF(
            this.options.player, "videomodalfeature",
            dims[0],              dims[1],
            swfVersionStr,        xiSwfUrlStr,
            flashvars,            params,
            attributes
        );
    },
    
    addEvents: function () {
    	var th = this 
    	$('a',this.element).click(function(){
    		console.log("open");
    		th.show();
    		return false;
    	});
    	$('.close').click(function(){
    		console.log("close");
    		th.hide();
    	});
    	
    }   
});

