function clickVid(e) {

	if (e.data.emb > '') {
		Shadowbox.open({
			content:	e.data.emb,
			player:     "swf",
			height:     344,
			width:      425
		});
		
		return false;
	}
}

function stadium_switch(newstad) {
	if (admin_stadium == STAD_character.stadium) extra=''; else extra=admin_stadium+'s';
	$("#chatlist"+extra).hide();
	$("#predictlist"+extra).hide();
	$("#crowdlist"+extra).hide();

	if (newstad == STAD_character.stadium) extra=''; else extra=newstad+'s';
	$("#chatlist"+extra).show();
	$("#predictlist"+extra).show();
	$("#crowdlist"+extra).show();

	admin_stadium = newstad;
}

function radio_status(new_streaming,new_playing) {
	if (!new_streaming) {
		$("#radio_icon").attr("src","http://www.luddweb.com/iploughlane/images/misc/radio_offair.gif");
		radio_streaming = false;
		if (radio_playing) document.radio.Stop()
		radio_playing = false;
	}
	else {
		radio_streaming = true;
		if (new_playing) {
			$("#radio_icon").attr("src","http://www.luddweb.com/iploughlane/images/misc/radio_on.gif");
			if (!radio_playing) document.radio.Play();
		}
		else {
			$("#radio_icon").attr("src","http://www.luddweb.com/iploughlane/images/misc/radio_off2.gif");
			if (radio_playing) document.radio.Stop();
		}
		radio_playing = new_playing;
	}
}

function clean(data) {
//	data = data.replace(/(http:\/\/)(.*)\s/gi, '<a href=../../modules/$1$2>$1$2 target="_blank"</a>');
    data = data.replace(exp,'<a href="$1" target="_blank">$1</a>'); 
	if (swearing_permit == false) {
		newval = data.replace(bw, ReplacementText);
		if (newval.length != data.length ||  newval != data) data = newval;
	}
	return data;
}

function sendmessage(chan) {
	var stad=STAD_character.stadium;
	
	switch (chan) {
		case 'w':
		case 'm':
			message = $.trim($("#chatmess").val());
			$("#chatmess").val('');
			break;
		case 'e':
			message = $.trim($("#predictmess").val());
			$("#predictmess").val('');
			break;
	}

	if (message > '') {
		if (STAD_response.user_admin == 1) stad=admin_stadium;
		$.ajax({
			type: "POST",
			url: "methods/mess.php",
			data: "force="+dummy.getTime()+"&stad="+stad+"&m="+chan+"&t="+encodeURIComponent(message),
			success: function(msg) { message_poll(); },
			datatype: "text"
		});
	}
	return false;
}

function wimpyPopPlayer(theFile,id,stuff) {
	if (WinId[0] && !WinId[0].closed) return false;
	WinId[0]=window.open(theFile,id,stuff);
}

function crowd_kick(e) {
	if (confirm('Kick ' + e.data.name + '?')) {
		$.ajax({
			type: "POST",
			url: "methods/kick.php",
			data: "force="+dummy.getTime() + "&id=" + e.data.seat + "&ip=" + e.data.ip+"&stad=" + e.data.stad+"&ban=0"
		});
	}
}

function crowd_ban(e) {
	if (confirm('Permanently ban ' + e.data.name + '?')) {
		$.ajax({
			type: "POST",
			url: "methods/kick.php",
			data: "force="+dummy.getTime() + "&id=" + e.data.seat + "&ip=" + e.data.ip+"&stad=" + e.data.stad+"&ban=1"
		});
	}
}

function crowd_bounce(sid,n) {
	while (n>0) {
		$("#seat"+sid).animate({"bottom": "+=20px"}, "fast").animate({"bottom": "-=20px"}, "fast");
		n--;
	}
	return false;
}

function crowd_jump() {
	px = (11+Math.floor(Math.random()*10));
	$('#crowd').animate({'bottom': '+='+px+'px'}, 'fast').animate({'bottom': '-='+px+'px'}, 'fast').animate({'bottom': '+='+px+'px'}, 'fast').animate({'bottom': '-='+px+'px'}, 'fast');
	return false;
}

function clock_update() {
var elapsed = time_now - time_period_started + time_base;
var secs = elapsed % 60;
var mins = parseInt(elapsed / 60);
if (secs < 10) secs = '0'+secs;
$("#scoreboard_clock").html(mins + ":" + secs);
}

function tab_switch(which) {
	switch (which) {
		case 1 :
			$("#updatewin").show();
			$("#scorewin").hide();
			$("#picwin").hide();
			$("#vidwin").hide();
			$("#updatetab").removeClass("tab_alert");
			$("#updatetab").addClass("tab_sel");
			if (!score_unseen) $("#scoretab").removeClass();
			if (!pic_unseen) $("#pictab").removeClass();
			if (!vid_unseen) $("#vidtab").removeClass();
			update_unseen = false;
			break;
		case 2 :
			$("#updatewin").hide();
			$("#scorewin").show();
			$("#picwin").hide();
			$("#vidwin").hide();
			$("#scoretab").removeClass("tab_alert");
			$("#scoretab").addClass("tab_sel");
			if (!update_unseen) $("#updatetab").removeClass();
			if (!pic_unseen) $("#pictab").removeClass();
			if (!vid_unseen) $("#vidtab").removeClass();
			score_unseen = false;
			break;
		case 3 :
			$("#updatewin").hide();
			$("#scorewin").hide();
			$("#picwin").show();
			$("#vidwin").hide();
			$("#pictab").removeClass("tab_alert");
			$("#pictab").addClass("tab_sel");
			if (!update_unseen) $("#updatetab").removeClass();
			if (!score_unseen) $("#scoretab").removeClass();
			if (!vid_unseen) $("#vidtab").removeClass();
			pic_unseen = false;
			break;
		case 5 :
			$("#updatewin").hide();
			$("#scorewin").hide();
			$("#picwin").hide();
			$("#vidwin").show();
			$("#vidtab").removeClass("tab_alert");
			$("#vidtab").addClass("tab_sel");
			if (!update_unseen) $("#updatetab").removeClass();
			if (!score_unseen) $("#scoretab").removeClass();
			if (!pic_unseen) $("#pictab").removeClass();
			vid_unseen = false;
			break;
		case 4 :
			$("#chatwin").show();
			$("#predictwin").hide();
			$("#crowdwin").hide();
			$("#chattab").addClass("tab_sel");
			$("#predicttab").removeClass();
			$("#crowdtab").removeClass();
			break;
		case 7 :
			$("#chatwin").hide();
			$("#predictwin").hide();
			$("#crowdwin").show();
			$("#chattab").removeClass();
			$("#predicttab").removeClass();
			$("#crowdtab").addClass("tab_sel");
			break;			
		case 6 :
			$("#chatwin").hide();
			$("#predictwin").show();
			$("#crowdwin").hide();
			$("#chattab").removeClass();
			$("#predicttab").addClass("tab_sel");
			$("#crowdtab").removeClass();
			break;			
	}
}

function second_loop() {
	loop_count++;
	if (match_period == 1 || match_period == 3) {
		time_now += 1;
		clock_update();
	}
	if (loop_count >= crowd_count/13 && loop_count >=6) {
		if (debug) console.log('Loop ' + loop_count);
		loop_count=0;
		message_poll();
	}
}

function message_poll() {
	if (STAD_response.user_admin == 1)
		$.ajax({
			type: "POST",
			url: "methods/arpc.php",
			data: "req="+request+'&force='+dummy.getTime(),
			success: function(msg) { handleResponse(msg); },
			error: function(XMLHttpRequest, textStatus, errorThrown) {
			},
			datatype: "text",
			timeout: "5000"
		});
	else
		$.ajax({
			type: "POST",
			url: "methods/rpc.php",
			data: "req="+request+'&force='+dummy.getTime(),
			success: function(msg) { handleResponse(msg); },
			error: function(XMLHttpRequest, textStatus, errorThrown) {
			},
			datatype: "text",
			timeout: "5000"
		});
}

function handleResponse(response) {
	var respline = new Array();
	var update = new Array();
	var this_stad = STAD_character.stadium;
	var extra='';

	if (instadium=false) return;
	if (debug) console.log('handleResponse');
	if(response.indexOf('#') != -1) {
		respline = response.split('#');
	    if (debug) console.log(request + '; ' + respline[0] + '; ' + respline.length);
		var newreq = Number(respline[0]);
		if (newreq == -1) {
			stadium_exit(false);
			alert('The stadium is now closed. Please have a safe journey home.');  // stadium closed
		}
		if (newreq == 0) {
			stadium_exit(false);
			alert('You have been removed from the stadium. This could be because a season ticket holder needed your place, your computer stopped communicating with the server, or you were ejected by the administrator.');  // kicked or logged out by time
		}
		crowd_count = respline[2];
		$("#scoreboard_att").html('Att: '+crowd_count);
		if (newreq > request) {
			seats_changed = false;
			for (i=3; i<respline.length; i++) {
				update = respline[i].split('|');
				if (STAD_response.user_admin == 1) {
					this_stad=update[0];
					update.splice(0,1);
					if (this_stad == STAD_character.stadium)
						extra='';
					else
						extra = this_stad+'s';
				}
			    if (debug) console.log('*' + respline[i] + '*');
				switch (update[0]) {
					case 't': // teams
						$("#scoreboard_clock").html('0:00');
						$("#scoreboard_ht").html(update[1]);
						$("#scoreboard_at").html(update[2]);
						$("#scoreboard_hs").html(update[3]);
						$("#scoreboard_as").html(update[4]);
						break;
					case 'e': // predict
						$("#predictlist"+extra).prepend('<p><strong>'+clean(update[1])+'</strong>: '+clean(update[2])+'</p>');
						break;
					case 'm': // message
						$("#chatlist"+extra).prepend('<p'+((update[3]==3)?' class="chat_oppo"':'')+'><strong>'+clean(update[1])+'</strong>: '+clean(update[2])+'</p>');
						break;
					case 'w': // admin message
						$("#chatlist"+extra).prepend('<p class="admin_message"><strong>'+clean(update[1])+'</strong>: '+clean(update[2])+'</p>');
						break;
					case 'h': // start/end half
					case 'u': // update
					case 'p': // scoreflash
						if (update[0] == 'p' || update[0] == 'h') {
							update[2]='<strong>'+update[2]+'</strong>';
						}
						$('#updatelist').prepend('<p><strong>'+update[1]+'</strong>: '+clean(update[2])+'</p>');
						if (update[0] == 'p' && request>0 && update[3] == 1) crowd_jump();
						if (update[0] == 'h') {
							match_period = Number(update[3])+1;
							if (match_period == 1) {
								time_period_started = update[4];
								time_base = 0;
							}
							else if (match_period == 3) {
								time_period_started = update[4];
								time_base = 45*60;
							}
						}
						break;
						if ($('#updatetab').hasClass('tab_alert') == false  && first_call == false) {
							$('#updatetab').addClass('tab_alert');
							update_unseen = true;
						}
						break;
					case 'g': // goal
						$("#scoreboard_hs").html(update[1]);
						$("#scoreboard_as").html(update[2]);
						break;
					case 's': // seat change
					case 'k': // seat kick
						seat_id = 'seat'+update[1];
						if (update[2] > '') {
							if ($("#list"+extra+update[1]).length == 0) {
								if (debug) console.log(extra+update[1]+' added');
								if (this_stad == STAD_character.stadium) {
									newD = '<div id="' + seat_id + '" class="avatar" style="position:absolute;';
									newD+= 'z-index:' + String((230-update[3])) + ';';
									if (update[3]<217) {
										div31 = parseInt(update[3] / 31);
										newD += 'bottom:' + String(7 + div31*20+Number(update[6]))+'px;';
										newD += 'left:' + String((update[3] % 31)*30+15*(div31 % 2)-17)+'px';
									}
									else {
										newD += 'bottom:' + String(232+Number(update[6]))+'px;';
										newD += 'left:' + String(320+(update[3]-217)*40)+'px';
									}
									newD += ';">';
									$('#crowd').append(newD);
									dy=0;
									for (j=7;j<update.length-1;j+=3) {
										$('#'+seat_id).append('<img src = "http://www.luddweb.com/iploughlane/images/crowd/'+PNGfile(update[j+1]) + '" style="bottom:' + String(dy)+'px;left:' + String(update[j])+'px;position:absolute" alt="'+update[2]+'" title="'+update[2]+'">');
										dy = Number(update[j+2]) + dy;
									}
								}
								var list_data = '<span id="name'+extra+update[1]+'" class="pointer">'+update[2]+'</span> ['+ticket_type[update[5]-1]+']';
								if (STAD_response.user_admin == 1) {
									list_data = '<img src="'+groot+'/misc/redcard.gif" id="r'+extra+update[1]+'" class="card pointer" />' + list_data;
									list_data = '<img src="'+groot+'/misc/yellowcard.gif" id="y'+extra+update[1]+'" class="card pointer" />' + list_data;
								}
								$("#crowdlist"+extra).append('<p id="list'+extra+update[1]+'">'+list_data+'</p>');
								if (this_stad == STAD_character.stadium) {
									$("#name"+update[1]).click( function (e) { crowd_bounce(e.target.id.substr(4),1); });
									seats_changed = true;
								}
								if (STAD_response.user_admin == 1) {
									$("#y"+extra+update[1]).bind('click',{ seat:update[1], ip: update[4], name:update[2], stad:this_stad }, function (e) { crowd_kick(e); });
									$("#r"+extra+update[1]).bind('click',{ seat:update[1], ip: update[4], name:update[2], stad:this_stad }, function (e) { crowd_ban(e); });
								}
							}
						}
						else {
							if ($("#list"+extra+update[1]).length > 0) {
							     if (debug) console.log(extra+update[1]+' removed');
								$("#list"+extra+update[1]).remove();
								if (this_stad == STAD_character.stadium) {
									if (update[0] == "k")
										$("#"+seat_id).attr("id","kick"+update[1]).animate({ 
											"bottom": "300px"
										}, "slow", function() { $(this).remove(); } );
									else
										$("#"+seat_id).remove();
								}
							}
						}
						break;
					case 'f': // new picture feed
						$("#piclist").prepend('<p><a href="'+update[3]+'" target="_blank">'+update[2]+'</a></p>');
						if ($('#pictab').hasClass('tab_alert') == false  && first_call == false) {
							$('#pictab').addClass('tab_alert');
							pic_unseen = true;
						}
						break;
					case 'v': // new video feed
						$("#vidlist").prepend('<p><a id="v-'+ update[1] +'" href="'+update[3]+'" target="_blank">'+update[2]+'</a></p>');
						$("#v-" + update[1]).bind("click", { emb: update[4] }, clickVid);
						if ($('#vidtab').hasClass('tab_alert') == false  && first_call == false) {
							$('#vidtab').addClass('tab_alert');
							vid_unseen = true;
						}
						break;
					case 'x': // scores
						$("#scorelist").html('<p>'+update[1]+'</p>');
						if ($('#scoretab').hasClass('tab_alert') == false  && first_call == false) {
//							$('#scoretab').addClass('tab_alert');
//							score_unseen = true;
						}
						break;
					case 'a' : // audio
						radio_status(update[1]==1,radio_playing);
						break;
				}
			}
			request = newreq;
			if (seats_changed) {
				$("#crowdlist>p").tsort("span.pointer");
			}
		}
		time_now = Number(respline[1]);
		if (match_period == 1 || match_period == 3) clock_update();
	}
}

var request;
var instadium, adminstadium;
var match_period, time_period_started, time_now, time_base, loop_count;
var update_unseen, crowd_unseen, pic_unseen, score_unseen, vid_unseen;
var radio_streaming, radio_playing;
var swearing_permit, interval_tag,first_call;
var ReplacementText = "***";
//edit the words here
//sorted alpha backwords to catch bad word groupings
var badwords=['wanking','w@nker','wanker','wank','twat','shit','sh!t','piss','pimp','niggers','nigger','motherfucking','motherfuckin','motherfuckers','motherfucker','motherfuck','fuk','fucks','fcuk','fck','fucking','fuckin','fuckers','fucker','fucked','fuck','cunts','cunt','cocksucking','cocksucker','cocksucked','cocksuck','cocks','cock','bollocks','bastard','bugger','mk dons','shroot','milton keynes','bollox','cvnt','fack'];
// var bw="\\b("+badwords.join("|")+")\\b";
var bw="("+badwords.join("|")+")";
bw=new RegExp(bw, "gi");
var ticket_type = ['Season ticket','Dons','Opponents'];
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;

function stadium_exit(voluntary) {
	instadium=false;
	window.clearInterval(interval_tag);
	if (voluntary)
		$.ajax({
			url: "methods/logout.php",
			data: "force="+dummy.getTime()
		});
	$("#stadium_wrapper").html('');
	$("#front_wrapper").show();
	$("#stadium_wrapper").hide();
}

function stadium_show() {
//	$("#stadium_wrapper").load('/admin/makestad.php?stadium_id='+STAD_stadium);

	$("#please_wait").show();
	$("#front_wrapper").hide();

	$("#stadium_wrapper").load('methods/stadium.php?template_id='+STAD_template, function() {

		radio_streaming = false;
		radio_playing = false;
	
		request = 0;
		update_unseen = false;
		crowd_unseen = false;
		pic_unseen = false;
		vid_unseen = false;
		score_unseen = false;
		swearing_permit = false;
		crowd_count = 0;
		match_period = 0;
		time_period_started = 0;
		time_now = 0;
		time_base = 0;
		loop_count = 0;
		first_call = true;
		tab_switch(1);
		tab_switch(4);

		if (STAD_response.user_admin == 0)
			$("#stewbutton").hide();
		else {
			$("#stewbutton").click(function () { return sendmessage('w') });
			$("#stewbutton").show();
			$("#adminstadium").change(function() { stadium_switch($(this).val()); });
			$(".adminwin").hide();
			admin_stadium = STAD_character.stadium;
		}

		$("#swearbox").removeAttr("checked").click(function() { swearing_permit = !swearing_permit; });
		$("#updatetab").click(function () { tab_switch(1) });
		$("#scoretab").click(function () { tab_switch(2) });
		$("#pictab").click(function () { tab_switch(3) });
		$("#vidtab").click(function () { tab_switch(5) });
		$("#chattab").click(function () { tab_switch(4) });
		$("#predicttab").click(function () { tab_switch(6) });
		$("#crowdtab").click(function () { tab_switch(7) });
		$("#chatform").submit(function () { return sendmessage('m') });
		$("#predictform").submit(function () { return sendmessage('e') });
		$("#jumpbutton").click(function () { crowd_jump() });
		$("#exit").click(function () { stadium_exit(true) });
		$("#radio_icon").click(function() { radio_status(radio_streaming,!radio_playing); });
		instadium=true;
		if (STAD_response.user_admin == 1) curl = 'agame_first.php';
		else curl = 'game_first.php';
		$.ajax({
			type: "POST",
			url: "methods/"+curl,
			async: false,
			data: "force="+dummy.getTime(),
			success: function(msg) {
				handleResponse(msg);
				$("#please_wait").hide();
				$("#stadium_wrapper").show();
				first_call = false;
				interval_tag = window.setInterval(second_loop,1000);
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				alert('Unable to load stadium');
				stadium_exit(false);
			},
			datatype: "text"
		});


	});
}