var titleflash_oldtitle = false;
var titleflash_flashtitle = false;
var titleflash_count = 0;
var titleflash_timer = false;
var viewport;

jQuery(function() {

	// If emoticons exist, activate them
	jQuery("#avemoticons img").click(avSelectEmoticon);

	jQuery("#txtmsg").keypress(function(e) { if (jQuery("#chksendonenter").get(0).checked && e.which==13) avSendMsg(); });
	jQuery("#avmarketschat").scroll(avMLScrollTimer);
	if (jQuery("#avmarketschat").length) jQuery("#avmarketschat").get(0).scrollTop = 999999;
	avResizeChat();

});

function avSendMsg() {
	var msg = jQuery("#txtmsg").val();
	if (msg.length > 4096) {
		alert("Message too long.  Please restrict messages to 4096 characters.");
		return false;

	} else if (msg.length > 0)	{
		// Strip all spans, as they may carry nasty word formatting
		var tempstring = "";
		while (tempstring.toString() != msg.toString()) {
			tempstring = msg;
			msg = msg.replace(/<span(.*?)>(.*?)<\/span>/i, "$2");
		}
		if (jQuery("#chkmsgasquote").get(0).checked) {
			msg = "<span class=\"quote\"><span>"+msg+"</span></span>";
			jQuery("#chkmsgasquote").get(0).checked = false;
			avQuoteChange();
		}
		jQuery("#btnsend").get(0).disabled = true;
		jQuery("#txtmsg").get(0).disabled = true;
		jQuery.post("http://"+location.hostname+"/marketslive/ashttp/sendmsg", {msg:encodeURIComponent(msg)}, function(resp) {
			jQuery("#txtmsg").get(0).disabled = false;
			jQuery("#btnsend").get(0).disabled = false;
			if (resp != '1' && resp.length < 200) alert(resp);
			else jQuery("#txtmsg").val("").get(0).focus();
		});
	}
	return false;
}

function avQuoteChange() {
	if (!jQuery("#chkmsgasquote").length || !jQuery("#txtmsg").length) return;
	if (jQuery("#chkmsgasquote").get(0).checked) {
		jQuery("#txtmsg").addClass("quote");
	} else {
		jQuery("#txtmsg").removeClass("quote");
	}
}

function ml_prepub(data) {
	var t = (avTime() / 1000);
	if (data.emb <= (t+servertimeoffset)) {
		ml_msg(data);
	} else if (data.mid > lastmlmsg) {
		lastmlmsg = data.mid;
		var parid = avParticipantKnown(data.author);
		if (typeof(parid) != "number") parid = avLookUpParticipant(data.author);
		try	{
			msg = decodeURIComponent(data.msg);
		} catch (err) {
			msg = "<em>[There was an error decoding this message]</em>";
		}
		msg = msg.replace(/\n/g, "<br />");
		if (data.author=="ZSYS") {
			var msghtml = "<div class=\"mlsysmsg\" timestamp=\""+data.timestamp+"\" id=\"mlp_" + data.mid + "\">";
		} else if (data.author=="ZQUO") {
			var msghtml = "<div class=\"mlquotmsg\" timestamp=\""+data.timestamp+"\" id=\"mlp_" + data.mid + "\">";
		} else if (data.author=="ZDIV") {
			var msghtml = "<div class=\"mlseparator\" timestamp=\""+data.timestamp+"\" id=\"mlp_" + data.mid + "\">";
		} else {
			var msghtml = "<div class=\"mlprepub\" timestamp=\""+data.timestamp+"\" id=\"mlp_" + data.mid + "\"><span class=\"parcol_" + parid +"\">" + data.author + "</span>";
		}
		msghtml += "<div>" + msg + "<a class=\"blocklink\" id=\"mlblocklink_"+data.mid+"\" href=\"javascript:void(0)\" onclick=\"avBlockMsg("+data.mid+")\">Block</a></div></div>";
		
		// Rearrange to cope with block quotes
		msghtml = msghtml.replace(/<\/span><\/span><a class=\"blocklink(.*?)<\/a>/i, "<a class=\"blocklink$1</a></span></span>");
		data.embdate = data.emb;
		mlprepubmsgs[mlprepubmsgs.length] = data;
		if (!jQuery("#mlp_" + data.mid).length) avMLUpdateScroll(msghtml);
	}
}

function ml_msg(data) {
	if (data.mid > lastmlmsg) {
		lastmlmsg = data.mid;
		var parid = avParticipantKnown(data.author);
		if (typeof(parid) != "number") parid = avLookUpParticipant(data.author);
		try	{
			msg = decodeURIComponent(data.msg);
		} catch (err) {
			msg = "<em>[There was an error decoding this message]</em>";
		}
		msg = msg.replace(/\n/g, "<br />");
		if (data.author=="ZSYS") {
			var msghtml = "<div class=\"mlsysmsg\" timestamp=\""+data.timestamp+"\" id=\"mlp_" + data.mid + "\">";
		} else if (data.author=="ZQUO") {
			var msghtml = "<div class=\"mlquotmsg\" timestamp=\""+data.timestamp+"\" id=\"mlp_" + data.mid + "\">";
		} else if (data.author=="ZDIV") {
			var msghtml = "<div class=\"mlseparator\" timestamp=\""+data.timestamp+"\" id=\"mlp_" + data.mid + "\">";
		} else {
			var msghtml = "<div class=\"mlmsg\" timestamp=\""+data.timestamp+"\" id=\"mlp_" + data.mid + "\"><span class=\"parcol_" + parid +"\">" + data.author + "</span>";
		}
		msghtml += "<div>" + msg + "</div></div>";
		if (!jQuery("#mlp_" + data.mid).length) avMLUpdateScroll(msghtml);
	}
}

function ml_block(data) {
	if (jQuery("#mlp_"+data.msgblocked).length) {
		if (!jQuery("#mlp_"+data.msgblocked).hasClass("mlblocked")) {
			jQuery("#mlp_"+data.msgblocked).addClass("mlblocked");
			jQuery("#mlp_"+data.msgblocked).append(" (blocked by "+data.blockedby+")");
			
			// Rearrange to cope with block quotes
			jQuery("#mlp_"+data.msgblocked).html(jQuery("#mlp_"+data.msgblocked).html().replace(/\s*(<\/span><\/span>)?\s*(<\/div>)?\s*\(blocked by (.*?)\)/im, " (blocked by $3)$2$1"));
			if (jQuery("#mlblocklink_"+data.msgblocked).length) jQuery("#mlblocklink_"+data.msgblocked).hide();
		}
	}
}

function ml_start() {
	if (location.href.indexOf("/marketslive/") != -1 && !jQuery("#avmarketschat").get(0)) {
		top.location.href = '/marketslive/?start=true&cb='+avTime();
	} else {
		av_highlightlivetab();
	}
}

function ml_end(data) {
	if (location.href.indexOf("/marketslive/") != -1 && jQuery("#avmarketschat").get(0)) {
		Meteor.disconnect();
		avMLUpdateScroll("<div class=\"mlsysmsg\"><div>This session of Markets Live has now closed, and the <a href=\""+data.guid+"\">full transcript is available</a> to view.</div></div>\n");
	}
	av_revertlivetab();
}

function av_readercount(data) {
	jQuery("#spnreadership").html(data.readers+" readers connected");
}

function av_revertlivetab() {
	if (jQuery("#lnknavml").hasClass("current")) jQuery("#lnknavml").css({width:'6.7em'});
	else jQuery("#lnknavml").css({width:'6.1em'});
	jQuery("#lnknavml").removeClass("live");
	jQuery("#lnkmarketslive").attr("href", "/marketslive").children("span").html("Markets live");
}


function avParticipantKnown(initials) {
	for (var i=0; i<mlparticipants.length; i++) {
		if (mlparticipants[i].initials == initials) {
			return i;
		}
	}
	return false;
}
function avBlockTick() {
	var now = new Date();
	var t = (now.getTime() / 1000);
	var newlist = new Array();
	if (typeof(pchannel) != "undefined") {
		for (var i=0; i<mlprepubmsgs.length; i++) {
			if (jQuery("#mlp_"+mlprepubmsgs[i].mid).length && !jQuery("#mlp_"+mlprepubmsgs[i].mid).hasClass("mlblocked")) {
				avenableautoscroll = false;
				if (mlprepubmsgs[i].embdate < (t+servertimeoffset)) {
					jQuery("#mlp_"+mlprepubmsgs[i].mid).removeClass("mlprepub").addClass("mlmsg");
					jQuery("#mlblocklink_"+mlprepubmsgs[i].mid).remove();
				} else {
					jQuery("#mlblocklink_"+mlprepubmsgs[i].mid).html("Block: "+Math.ceil(mlprepubmsgs[i].embdate-(t+servertimeoffset)));
					newlist[newlist.length] = mlprepubmsgs[i];
				}
				avenableautoscroll = true;
			}
		}
	}
	mlprepubmsgs = newlist;
	if (Meteor.mode == "smartpoll" || Meteor.mode=="simplepoll") {
		window.status="Markets live is updated every "+Math.floor(Meteor.pollfreq/1000)+" seconds.";
	} else {
		if (!isNaN(Meteor.lastpingtime)) {
			window.status="Markets live is streaming.";
			if (!connectmsg) {
				avMLUpdateScroll("<div class=\"mlsysmsg\"><div>Welcome to Markets Live.  New messages will appear here as they are posted.</div></div>");
				connectmsg = true;
			}
		}
	}

	setTimeout('avBlockTick()',1000);
}
function avRevertFormatting(htmlstring) {
	var tempstring = "";
	while (tempstring.toString() != htmlstring.toString()) {
		tempstring = htmlstring;
		htmlstring = htmlstring.replace(/<img(.*?)src="(.*?)\/lib\/img\/emoticons\/(.*?)\.(.*?)>/i, "{$3}");
	}
	htmlstring = htmlstring.replace(/<span(.*?)class=(.*?)quote(.*?)><span>(.*?)<\/span><\/span>/i, "$4");
	if (tempstring.toString() != htmlstring.toString()) {
		jQuery("#chkmsgasquote").get(0).checked = true;
		avQuoteChange();
	}
	htmlstring = htmlstring.replace(/^<span(.*?)class=\"?\'?parcol_[0-9]\"?\'?>[^<]*<\/span>/i, "");
	htmlstring = htmlstring.replace(/^\s*<div>\s*/im, "");
	htmlstring = htmlstring.replace(/\s*<\/div>\s*$/im, "");
	tempstring = "";
	while (tempstring.toString() != htmlstring.toString()) {
		tempstring = htmlstring;
		htmlstring = htmlstring.replace(/<br(.*?)>/i, "\n");
	}
	return htmlstring;
}
function avLookUpParticipant(inls) {
	if (inls == "ZSYS" || inls == "ZQUO" || inls == "ZDIV") return true;
	var n = mlparticipants.length;
	var url = 
	jQuery.getJSON("/marketslive/ashttp/participantdetails?q="+inls, function(response) {
		mlparticipants[n] = response;
		if (!jQuery("#mlpar"+inls).length) {
			jQuery("#mlparsempty").remove();
			jQuery("#mlpars").append("<span class='mlpar' id='mlpar"+inls+"'><span class='parcol_"+n+"'>"+response.initials+"</span> "+response.name+" &nbsp;</span>");
		}
	});
	return n;
}
function avBlockMsg(mid) {
	jQuery.get("/marketslive/ashttp/blockmsg?id="+mid);
	var blockdiv = jQuery("#mlblocklink_"+mid).get(0).cloneNode(true);
	jQuery("#mlblocklink_"+mid).remove();
	jQuery("#txtmsg").val(avRevertFormatting(jQuery("#mlp_"+mid).html()));
	jQuery("#mlp_"+mid).addClass("mlblocked").get(0).innerHTML += " (blocked by me)";
	
	// Rearrange to cope with block quotes
	jQuery("#mlp_"+mid).html(jQuery("#mlp_"+mid).html().replace(/\s*(<\/span><\/span>)?\s*(<\/div>)?\s*\(blocked by (.*?)\)/im, " (blocked by $3)$2$1"));
	jQuery("#mlp_"+mid).get(0).appendChild(blockdiv);
	jQuery("#mlblocklink_"+mid).hide();
}
function avSelectEmoticon(img) {
	img = img.target;
	if (img.title) {
		jQuery("#txtmsg").get(0).value += img.title;
	} else {
		jQuery("#txtmsg").get(0).value += "{"+img.src.substring((img.src.lastIndexOf("/")+1), img.src.lastIndexOf("."))+"}";
	}
	jQuery("#txtmsg").get(0).focus();
}


var avmlscrolltimer = null;
var avenableautoscroll = true;
var avanimating = false;
var scrollpos_ml = 0;
var scrollpos_inf = 0;

function avMLScrollTimer(e) {
	if (avmlscrolltimer) clearTimeout(avmlscrolltimer);
	if (jQuery('#chksyncscroll').get(0).checked && avenableautoscroll) {
		avmlscrolltimer = setTimeout(function() {
			if (avanimating) stopAnimations();
			var ml = jQuery('#avmarketschat');
			var inf = jQuery('#infernolist');
			var refoffset = (ml.outerHeight()/2) + ml.offset().top;
			var elmatch = null;

			// ML chat has been scrolled significantly
			if (jQuery(e.target).attr("id") == "avmarketschat") {
				ml.children("div").each(function() {
					if (jQuery(this).offset().top > refoffset) return false;
					elmatch = jQuery(this);
				});
				var ts = elmatch.attr("timestamp"), scrollos = 0;
				inf.children("li").each(function() {
					if (jQuery(this).attr("sortindex") > ts) return false;
					scrollos += jQuery(this).outerHeight();
				});
				scrollos -= (ml.outerHeight()/2);
				scrollos = Math.round(max(min(scrollos,(inf.get(0).scrollHeight-inf.height())),0));
				if (inf.get(0).scrollTop < (scrollos-50) || inf.get(0).scrollTop > (scrollos+50)) {
					avenableautoscroll = false;
					inf.scrollTo(scrollos, 500, {onAfter:showTimeSlice(refoffset, ts)});
					scrollpos_inf = scrollos;
				}

			// Inferno chat has been scrolled significantly
			} else {
				inf.children("li").each(function() {
					if (jQuery(this).offset().top > refoffset) return false;
					elmatch = jQuery(this);
				});
				var ts = elmatch.attr("sortindex"), scrollos = 0;
				ml.children("div").each(function() {
					if (jQuery(this).attr("timestamp") > ts) return false;
					scrollos += jQuery(this).outerHeight();
				});
				scrollos -= (ml.outerHeight()/2);
				scrollos = Math.round(max(min(scrollos,(ml.get(0).scrollHeight-ml.height())),0));
				if (ml.get(0).scrollTop < (scrollos-50) || ml.get(0).scrollTop > (scrollos+50)) {
					avenableautoscroll = false;
					ml.scrollTo(scrollos, 500, {onAfter:showTimeSlice(refoffset, ts)});
					scrollpos_ml = scrollos;
				}
			}
		}, 200);
	}
}

var ietimeslicetimer = false;
function showTimeSlice(offset, time) {
	return (function() {
		var tsdate = new Date(time*1000);
		var h = tsdate.getHours();
		var m = tsdate.getMinutes();
		if (h<10) h="0"+h;
		if (m<10) m="0"+m;
		var datestr = h+":"+m;
		if (datestr != jQuery('#avmltimeslice span').html()) {
			avanimating = true;
			setTimeout("avenableautoscroll=true", 200);
			offset -= jQuery("#avmaincontent").offset().top;
			jQuery('#avmltimeslice span').html(datestr);
			jQuery('#avmltimeslice').css("top", (offset-30)+'px').show().animate({opacity:1}, 200, function() { 
				jQuery(this).animate({opacity:0}, 2000, function() {
					jQuery('#avmltimeslice').hide();
					avenableautoscroll=true;
					avanimating = false;
				});
			});
		} else {
			avenableautoscroll=true;
			avanimating = false;
		}
	});
}
function stopAnimations() {
	clearTimeout(ietimeslicetimer);
	jQuery('#avmltimeslice').stop().css('opacity',0).hide();
	avanimating = false;
	avenableautoscroll=true;
}
function avMLUpdateScroll(newcontent) {
	var win = jQuery("#avmarketschat");
	var pos = win.get(0).scrollTop+win.height();
	var max = win.get(0).scrollHeight;
	if (typeof newcontent == "string") win.append(newcontent);
	if (pos > (max-50)) {
		avenableautoscroll = false;
		jQuery("#avmarketschat").get(0).scrollTop = 999999;
		scrollpos_ml = jQuery("#avmarketschat").get(0).scrollTop;
		setTimeout("avenableautoscroll = true;", 50);
	}
}
function avSyncTime() {
	jQuery.get("/lib/ajx/gettime?nocache="+avTime(), function(response) {
		var t = Math.round(avTime() / 1000);
		if (!isNaN(response)) servertimeoffset = response-t;
	});
}
function avTime() {
	var now = new Date();
	return now.getTime();
}
function avCloseInfernoForm() {
	jQuery("#infernoshowform").show();
	jQuery("#infernohideform").hide();
	jQuery("#frminferno").hide();
	avResizeInferno();
}
function avOpenInfernoForm() {
	jQuery("#infernoshowform").hide();
	jQuery("#infernohideform").show();
	jQuery("#frminferno").show();
	avResizeInferno();
}

function avToggleFullscreen() {
	jQuery('#lnkmlfullscreen').get(0).blur();
	if (jQuery('.avpagecontainer').width() > 972) {
		jQuery('.avpagecontainer').css('width', '972px');
		jQuery('#lnkmlfullscreen').html('Full screen');
		jQuery('#avmarketschat div div').css('width','470px');
	} else {
		jQuery('.avpagecontainer').css('width', '100%');
		jQuery('#lnkmlfullscreen').html('Normal view');
		jQuery('#avmarketschat div div').css('width','auto');
	}
}

jQuery(document).resize(avResizeHandler);
function avResizeHandler() {
	avResizeChat();
	avResizeInferno();
}
function avResizeChat() {
	if (jQuery('#avmarketssessionwrapper').length) {
		jQuery("#avmarketsliveloader").remove();
		var viewport = jQuery(window).height();
		var headheight = jQuery('#avmarketssessionwrapper').offset().top + jQuery('#avmarketslivefooter').outerHeight();
		var workingarea = max(viewport-headheight, 500);
		var paruiheight = jQuery("#avparticipantsinterface").outerHeight()+2;  // 2px border on main chat
		jQuery('#avmarketssessionwrapper').height(workingarea-paruiheight);
	}
}
function avResizeInferno() {
	var win = jQuery("#infernolist");
	if (win.length) {
		var pos = win.get(0).scrollTop+win.height();
		var smax = win.get(0).scrollHeight;
		if (pos > (smax-30)) {
			infernoscrollpending = true;
			setTimeout(avScrollInferno, 50);
		}

		var viewport = jQuery(window).height();
		var headheight = jQuery('#avmarketssessionwrapper').offset().top + jQuery('#avmarketslivefooter').outerHeight(); 
		var workingarea = max(viewport-headheight, 500);
		var useruiheight = jQuery("#infernopostform").outerHeight()+jQuery("#ribbonad").outerHeight();
		jQuery('#infernolist').height(workingarea-useruiheight);
		jQuery("#infernolist").scroll(avMLScrollTimer);
	}
}
function avScrollInferno() {
	jQuery('#avmarketslivepage').css('visibility','visible');
	jQuery('#avmarketsliveinferno').css('visibility','visible');
	if (infernoscrollpending) {
		avenableautoscroll = false;
		jQuery("#infernolist").get(0).scrollTop = 999999;
		scrollpos_inf = jQuery("#avmarketschat").get(0).scrollTop;
		infernoscrollpending=false;
		setTimeout("avenableautoscroll = true;", 50);
	}
}


function min() {
	var v = Infinity;
	for( var i = 0;  i < arguments.length;  i++ ) {
		var n = arguments[i];
		if( n && n < v ) v = n;
	}
	return v;
}
function max() {
	var v = 0;
	for( var i = 0;  i < arguments.length;  i++ ) {
		var n = arguments[i];
		if( n && n > v ) v = n;
	}
	return v;
}

