	var dispatchEventHandle;
	var dispatchEventList = [];
	
	function scheduleMatchUpdate()
	{
		var updater = function() {
				var data = "";
                                //console.log(matchLastEventId);
				$.each(matchLastEventId, 
					function(k,v) { 
						data += "&lastEvents[" + k + "]=" + v;
					 });
				$.get(
					'/' + currMod + '/' + currCtrl + '/' + currMatch + '/update-match-info?' + data,
					function(data)
					{
						eval(data); // Will set variable EEventsFromServer to contain the new events;
						// run function specific for current controller
						try{
							eval(currCtrl + 'Events(EEventsFromServer)');
						}catch(err)
						{}
						
						// Add to list
						dispatchEventList = dispatchEventList.concat(EEventsFromServer);
						
						for(i = 0; i < EEventsFromServer.length; i++) {
							matchId = parseInt(EEventsFromServer[i].relatedMatch,10);
							eventId = parseInt(EEventsFromServer[i].idEvent,10);
							eventTime = parseInt(EEventsFromServer[i].timeInMatchInSeconds,10);
                                                        //console.log(eventTime);
							matchLastEventId[matchId] = Math.max(matchLastEventId[matchId], eventTime);
						}
						
						/*if(currMod == 'live')
							$('#clock').html(Math.round(matchLastEventId[currMatch] / 60)+"'");*/
						
						// Start with the new stuff now.
						clearTimeout(dispatchEventHandle);
						dispatchEvent();
					}
				);
				scheduleMatchUpdate();
			};
		setTimeout(updater,30000);
		restartTimer();
	}
	
	function dispatchEvent()
	{
		var event = dispatchEventList.shift();
		if(event){
			matchId = parseInt(event.relatedMatch,10);
			team = event.p1Side;
			// fire it
			globalEventUpdate(matchId,team.toLowerCase() ,event);
			
			dispatchEventHandle = setTimeout(dispatchEvent,5000);
		}
		
	}


function globalEventUpdate(matchID,team,event) {
	try{
		console.log(event);
	}catch(e){
	}

	eventSidebar(matchID,team,event);
	//live -active match
	if(currMod == 'live' && currMatch == matchID)
		eventActive(matchID,team,event);
}

function eventActive(matchID,team,event) {
	var eventTime = Math.round(event.timeInMatchInSeconds/60);
	var eventType = event.eventType;
	var playerName = event.p1ShirtName;
	var playerId = event.p1Id;
	var playerNameSecond = event.p2ShirtName;
	var playerIdSecond = event.p2Id;

	try{
		console.log(event);
	}catch(e){
	}
	//live & active
	var tmpHomeScore = parseInt( $("#home-score").text() ,10);
	var tmpAwayScore = parseInt( $("#away-score").text() ,10);
	
	//eventtype
	switch (eventType) {
		case 'scoring':
			if(team == 'home') { 
				tmpHomeScore = tmpHomeScore + 1; 
				if(tmpHomeScore < 2) { spacer = ''; } else { spacer = ', '; }
			} else { 
				tmpAwayScore = tmpAwayScore + 1;
				if(tmpAwayScore < 2) { spacer = ''; } else { spacer = ', '; }
			}
			
			$("#"+team+"-score").fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(300).fadeOut(300).fadeIn(300).fadeOut(400).fadeIn(400, function() {
				//update score
				$("#home-score").text( tmpHomeScore );
				$("#away-score").text( tmpAwayScore );

				//player
				$("#"+team+"-events ul.events-goal").append("<li>"+spacer+"<a href='/player/"+playerId+"'>"+playerName+"</a> ("+eventTime+")</li>");
				$("#"+team+"-events ul.events-goal li:last-child");
			});
		break;

		case 'owngoal':
			var oppTeam;
			
			if(team == 'away') { 
				tmpHomeScore = tmpHomeScore + 1; 
				if(tmpHomeScore < 2) { spacer = ''; } else { spacer = ', '; }
				oppTeam = 'home';
			} else { 
				tmpAwayScore = tmpAwayScore + 1;
				if(tmpAwayScore < 2) { spacer = ''; } else { spacer = ', '; }
				oppTeam = 'away';
			}
			

			$("#"+oppTeam+"-score").fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(300).fadeOut(300).fadeIn(300).fadeOut(400).fadeIn(400, function() {
				//update score
				$("#home-score").text( tmpHomeScore );
				$("#away-score").text( tmpAwayScore );

				//player
				$("#"+oppTeam+"-events ul.events-goal").append("<li>"+spacer+"<a href='/player/"+playerId+"'>"+playerName+"</a> ("+eventTime+")</li>");
				$("#"+oppTeam+"-events ul.events-goal li:last-child");
			});
		break;

		case 'penalty-score':
			if(team == 'home') { 
				tmpHomeScore = tmpHomeScore + 1; 
				if(tmpHomeScore < 2) { spacer = ''; } else { spacer = ', '; }
			} else { 
				tmpAwayScore = tmpAwayScore + 1;
				if(tmpAwayScore < 2) { spacer = ''; } else { spacer = ', '; }
			}
			
			$("#"+team+"-score").fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(300).fadeOut(300).fadeIn(300).fadeOut(400).fadeIn(400, function() {
				//update score
				$("#home-score").text( tmpHomeScore );
				$("#away-score").text( tmpAwayScore );

				//player
				$("#"+team+"-events ul.events-goal").append("<li><a href='/player/"+playerId+"'>"+playerName+"</a> ("+eventTime+")</li>");
				$("#"+team+"-events ul.events-goal li:last-child");

			});
		break;
		
		case 'penalty-miss':
			$("#"+team+"-events ul.events-other").append("<li><img src='/images/pitch/actions/"+eventType+".png' />&nbsp;&nbsp;<a href='/player/"+playerId+"'>"+playerName+"</a> ("+eventTime+")</li>");
			$("#"+team+"-events ul.events-other li:last-child").fadeIn(300).fadeOut(300).fadeIn(300).fadeOut(300).fadeIn(300);
		break;

		case 'booking':
			$("#"+team+"-events ul.events-other").append("<li><img src='/images/pitch/actions/"+eventType+".png' />&nbsp;&nbsp;<a href='/player/"+playerId+"'>"+playerName+"</a> ("+eventTime+")</li>");
			$("#"+team+"-events ul.events-other li:last-child").fadeIn(300).fadeOut(300).fadeIn(300).fadeOut(300).fadeIn(300);
		break;
		
		case 'sentoff':
			$("#"+team+"-events ul.events-other").append("<li><img src='/images/pitch/actions/"+eventType+".png' />&nbsp;&nbsp;<a href='/player/"+playerId+"'>"+playerName+"</a> ("+eventTime+")</li>");
			$("#"+team+"-events ul.events-other li:last-child").fadeIn(300).fadeOut(300).fadeIn(300).fadeOut(300).fadeIn(300);
		break;

		case 'substitution':
			$("."+team+"-lineup #lineupP"+playerId+" td:eq(1)").append(" (<img src='/images/pitch/sub_out.png' /> "+eventTime+")");
			$("."+team+"-subs #lineupP"+playerIdSecond+" td:eq(1)").append(" (<img src='/images/pitch/sub_in.png' /> "+eventTime+")");
		break;

		case 'delete':
                    location.reload(true);
                break;


	}


	//common
	switch (eventType) {
		case 'booking':
		case 'sentoff':
		case 'bookingsentoff':
		case 'substitution':
		case 'penalty-score':
		case 'penalty-miss':
			$("#btn"+team+"Events").hide();
			$("#"+team+"EventsImage").css("background-image","url('/images/pitch/actions/"+eventType+".png')").fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200, function() {
				$("#btn"+team+"Events").show();
				$("#btn"+team+"Events").css("text-decoration","underline");
			});
		break;
	}


}



function eventSidebar(matchID,team,event) {
	var eventType = event.eventType;

	//pregame or inactive
	var tmpHomeScore = parseInt( $("ul.fixtures li#match"+matchID+" .live-container .live .home-score").text(),10 );
	var tmpAwayScore = parseInt( $("ul.fixtures li#match"+matchID+" .live-container .live .away-score").text(),10 );	
	
	//audio
	audioPlayer(eventType);
	
	//eventtype
	switch (eventType) {
		case 'scoring':
			if(team == 'home') { tmpHomeScore = tmpHomeScore + 1; } else { tmpAwayScore = tmpAwayScore + 1;	}
			$("ul.fixtures li#match"+matchID+" .live-container .live").fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(300).fadeOut(300).fadeIn(300).fadeOut(400).fadeIn(400, function() {
				//update score
				$("ul.fixtures li#match"+matchID+" .live-container .live .home-score").text( tmpHomeScore );
				$("ul.fixtures li#match"+matchID+" .live-container .live .away-score").text( tmpAwayScore );
			});

			//mark sidebar?
			if(currMatch !== matchID) {
				$("ul.fixtures li#match"+matchID+" .live-container").css("border-left","2px solid #FEB92E"); 
			}
		break;

		case 'owngoal':
			if(team == 'away') { tmpHomeScore = tmpHomeScore + 1; } else { tmpAwayScore = tmpAwayScore + 1;	}
			$("ul.fixtures li#match"+matchID+" .live-container .live").fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(300).fadeOut(300).fadeIn(300).fadeOut(400).fadeIn(400, function() {
				//update score
				$("ul.fixtures li#match"+matchID+" .live-container .live .home-score").text( tmpHomeScore );
				$("ul.fixtures li#match"+matchID+" .live-container .live .away-score").text( tmpAwayScore );
			});

			//mark sidebar?
			if(currMatch !== matchID) {
				$("ul.fixtures li#match"+matchID+" .live-container").css("border-left","2px solid #FEB92E"); 
			}
		break;

		case 'booking':
			$("ul.fixtures li#match"+matchID+" .icon-container").show();
			$("ul.fixtures li#match"+matchID+" .icon").css("background","url(/images/pitch/actions/booking.png) center no-repeat");
			$("ul.fixtures li#match"+matchID+" .icon").fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(300).fadeOut(300).fadeIn(300).fadeOut(400, function() { 
				$("ul.fixtures li#match"+matchID+" .icon-container").hide();
			});

			//mark sidebar?
			if(currMatch !== matchID) {
				$("ul.fixtures li#match"+matchID+" .live-container").css("border-left","2px solid #FEB92E"); 
			}
		break;

		case 'sentoff':
			$("ul.fixtures li#match"+matchID+" .icon-container").show();
			$("ul.fixtures li#match"+matchID+" .icon").css("background","url(/images/pitch/actions/sentoff.png) center no-repeat");
			$("ul.fixtures li#match"+matchID+" .icon").fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(300).fadeOut(300).fadeIn(300).fadeOut(400, function() {
				$("ul.fixtures li#match"+matchID+" .icon-container").hide();
			});

			//mark sidebar?
			if(currMatch !== matchID) {
				$("ul.fixtures li#match"+matchID+" .live-container").css("border-left","2px solid #FEB92E"); 
			}
		break;

		case 'bookingsentoff':
			$("ul.fixtures li#match"+matchID+" .icon-container").show();
			$("ul.fixtures li#match"+matchID+" .icon").css("background","url(/images/pitch/actions/bookingsentoff.png) center no-repeat");
			$("ul.fixtures li#match"+matchID+" .icon").fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(300).fadeOut(300).fadeIn(300).fadeOut(400, function() {
				$("ul.fixtures li#match"+matchID+" .icon-container").hide();
			});

			//mark sidebar?
			if(currMatch !== matchID) {
				$("ul.fixtures li#match"+matchID+" .live-container").css("border-left","2px solid #FEB92E"); 
			}
		break;
		
		case 'substitution':
			$("ul.fixtures li#match"+matchID+" .icon-container").show();
			$("ul.fixtures li#match"+matchID+" .icon").css("background","url(/images/pitch/actions/substitution.png) center no-repeat");
			$("ul.fixtures li#match"+matchID+" .icon").fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(300).fadeOut(300).fadeIn(300).fadeOut(400, function() {
				$("ul.fixtures li#match"+matchID+" .icon-container").hide();
			});

			//mark sidebar?
			if(currMatch !== matchID) {
				$("ul.fixtures li#match"+matchID+" .live-container").css("border-left","2px solid #FEB92E"); 
			}
		break;

		case 'penalty-score':
			if(team == 'home') { tmpHomeScore = tmpHomeScore + 1; } else { tmpAwayScore = tmpAwayScore + 1;	}
			$("ul.fixtures li#match"+matchID+" .icon-container").show();
			$("ul.fixtures li#match"+matchID+" .icon").css("background","url(/images/pitch/actions/penalty-score.png) center no-repeat");
			$("ul.fixtures li#match"+matchID+" .icon").fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(300).fadeOut(300).fadeIn(300).fadeOut(400, function() { 
				$("ul.fixtures li#match"+matchID+" .live-container .live .home-score").text( tmpHomeScore );
				$("ul.fixtures li#match"+matchID+" .live-container .live .away-score").text( tmpAwayScore );
				$("ul.fixtures li#match"+matchID+" .icon-container").hide();
			});

			//mark sidebar?
			if(currMatch !== matchID) {
				$("ul.fixtures li#match"+matchID+" .live-container").css("border-left","2px solid #FEB92E"); 
			}
		break;

		case 'penalty-miss':
			$("ul.fixtures li#match"+matchID+" .icon-container").show();
			$("ul.fixtures li#match"+matchID+" .icon").css("background","url(/images/pitch/actions/penalty-miss.png) center no-repeat");
			$("ul.fixtures li#match"+matchID+" .icon").fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(300).fadeOut(300).fadeIn(300).fadeOut(400, function() { 
				$("ul.fixtures li#match"+matchID+" .icon-container").hide();
			});

			//mark sidebar?
			if(currMatch !== matchID) {
				$("ul.fixtures li#match"+matchID+" .live-container").css("border-left","2px solid #FEB92E"); 
			}
		break;
	}
	
	
	
	

	
}
// Called from all /live/* ajax call
function progressUpdated(matchStatus, timeInMatch)
{
	var text = '';
	
	switch(matchStatus) {
		case 'Started':
		case 'SecondHalf':
		case 'ExtraTimeStarted':
			text = secondsToGametime(timeInMatch);
			break;
		case 'HalfTime':
			text = 'H/T';	
			break;
		case 'Finished':
			text = 'F/T';
			break;
		case 'NotStarted':
			text = 'N/A';
			break;
		default:
			text = matchStatus;
	}

	$('#clock').html(text);
}

$(document).ready(function(){
	if(currMod =='live')
		tickTime();
});

var clockTimer;
// Makes the matchtimer tick
function tickTime() {
	if(clockTimer)
		clearTimeout(clockTimer);
	clockTimer = setTimeout('tickTime()',1000);
	
	var time = jQuery.trim($('#clock').text());
	var minsecArr = time.split(':');
	if(minsecArr.length != 2)
		return;
	var secs = parseInt(minsecArr[0],10)*60 + parseInt(minsecArr[1],10) + 1;

	var secondsInGame = secondsToGametime(secs);

	$('#clock').html(secondsInGame);
}

function secondsToGametime(seconds) {
	var mins = Math.floor(seconds/60).toString();
	var secs = (seconds % 60).toString();
	if(secs.length < 2)
		secs = "0" + secs;
	return mins + ":" + secs;
}

//pitch math
var leftOffset = 72;
var topOffset = 465;
var alpha = 90-10.05;
var fieldHeight = 375;
var fieldLength = 600;

// X in [0;1000], Y in [0;1000]
// does not take into account the elements width/height
function pitchPlaceElement(elem,x,y) {
	if(x > 0 || y > 0) {
		elem = $(elem);
		var cords = convertCords(parseFloat(x),parseFloat(y));
		
		$(elem).css('top', cords['x'] + 'px');
		$(elem).css('left', cords['y'] + 'px');
	}
	else {
		$(elem).remove();
	}
}

function convertCords(x,y) {

	var alphaRad = ((alpha / 180) * 3.14);
	var x = ((x/1000) * fieldLength);
	var y = (((1000-y)/1000) * fieldHeight);
	
	var u = ((Math.cos(alphaRad)*x) + (Math.sin(alphaRad)*y));
	var v = ((Math.sin(alphaRad)*x) - (Math.cos(alphaRad)*y));

	var CordTop = (topOffset - u);
	var CordLeft = (leftOffset + v);
	return { 'x': CordTop, 'y': CordLeft };
}

function pitchGetPlaceX(x) {
	var alphaRad = (alpha / 180) * 3.14;
	var x = (x/1000) * fieldLength;
	
}

function pitchGetPlaceY(y) { }


function restartTimer() {
	if(currMod == 'pregame' || currMod == 'live') {

		var flashvars = {
			time: "30",
			direction: "CLOCKWISE" // direction: CLOCKWISE/ANTICLOCKWISE
		};
		var params = {
			menu: "false",
			scale: "noScale",
			bgcolor: "#1F1F1F",
			wmode: "transparent"
		};
		swfobject.embedSWF("/flash/live_timer.swf", "timer-flash", "78", "78", "9.0.0", "/flash/expressInstall.swf", flashvars, params);
	
	}
}



function audioPlayer(eventType) {

	//sound on?
	if( $("#pref-audio").attr("checked") ) {
	
		//goal?
		switch (eventType) {
			case 'scoring':
			case 'owngoal':
			case 'penalty-score':
				$("#audioPlayer").attr("src","/audio/?src=scoring");
			break;
		}
		
	}
	
}



function teamStats(type,home,away) {

	switch (type) {
		case "possession":
			$("#stats-"+type+"-home span").html( Math.round(home) + "%" );
			$("#stats-"+type+"-away span").html( Math.round(away) + "%" );
		break;
		case "shotsOnTarget":
			$("#stats-"+type+"-home span").html( Math.round(home) );
			$("#stats-"+type+"-away span").html( Math.round(away) );


			//highest
			if(home > away) {
				$("#stats-"+type+"-home img").attr("src","/images/common/arrowUp.png");	
				$("#stats-"+type+"-away img").attr("src","/images/common/arrowDown.png");	
			} else if (home < away) {
				$("#stats-"+type+"-home img").attr("src","/images/common/arrowDown.png");	
				$("#stats-"+type+"-away img").attr("src","/images/common/arrowUp.png");	
			} else {
				$("#stats-"+type+"-home img").attr("src","/images/common/arrowUp.png");	
				$("#stats-"+type+"-away img").attr("src","/images/common/arrowUp.png");
			}

		break;
	}
	
}
