var shoutCheckTimeout = 10;

function GetXMLHttpRequest(type, url)
{
	var xmlhttp = null;
	if (window.XMLHttpRequest) {
			xmlhttp = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}  else {
			alert('Perhaps your browser does not support xmlhttprequests?');
	}
	if (xmlhttp)
	{
		xmlhttp.open(type, url, true);
		xmlhttp.setRequestHeader("Connection", "close");
	}

	return xmlhttp;
}

function CheckTag(gamertag, resultId)
{
	var url = "core_ajax.php?CheckTag=" + escape(gamertag);

	document.getElementById(resultId).innerHTML = "<img src='http://images.backofthenet.info/loading.gif' alt='' /> Checking tag status...";

	var xmlhttp = GetXMLHttpRequest('GET', url);

	// Set the callback function
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
		{
			var output = '';
			//alert(xmlhttp.responseText);
			if (xmlhttp.responseText == 0) { output = 'This gamertag does not exist'; }
			if (xmlhttp.responseText == 1) { output = 'Silver XBOX Live Membership found'; }
			if (xmlhttp.responseText == 2) { output = 'Gold XBOX Live Membership found'; }
			document.getElementById(resultId).innerHTML = output;
		}
		else {
			// waiting for the call to complete
		}
	};

	// Make the actual request
	xmlhttp.send(null);

	return false;
}

function opacity(id, opacStart, opacEnd, millisec) 
{
    //speed for each frame
    var speed = Math.round(millisec / 100);
    var timer = 0;

    //determine the direction for the blending, if start and end are the same nothing happens
    if(opacStart > opacEnd) {
        for(i = opacStart; i >= opacEnd; i--) {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    } else if(opacStart < opacEnd) {
        for(i = opacStart; i <= opacEnd; i++)
            {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    }
}

//change the opacity for different browsers
function changeOpac(opacity, id) {
    changeLoc(opacity, id);

    var object = document.getElementById(id).style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
}


function changeLoc(loc, id) {
    //window.status = loc + "%";
    //document.getElementById(id).style.height = loc/18 + "%";
}


function GetMessages(start, count, type, search)
{
	var url = "/core_ajax.php?action=GetMessages&s="+start+"&c="+count + "&type=" + type + "&search=" + encodeURI(search);
	//document.getElementById('inbox').innerHTML = "<img src='/sitepics/loading.gif' /> Loading messages...";

	var xmlhttp = GetXMLHttpRequest('GET', url);

	// Set the callback function
	xmlhttp.onreadystatechange = function()
	{
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
		{
			document.getElementById('inbox').innerHTML = xmlhttp.responseText;
		}
		else {
			// waiting for the call to complete
		}
	};

	// Make the actual request
	xmlhttp.send(null);
}


function GetMessage(id)
{
	var url = "/core_ajax.php?GetMessage=" + id;

	//document.getElementById('message').innerHTML = "<img src='http://images.backofthenet.info/loading.gif' /> Loading Message...";
	ShowPopup("View message", "", "<img src='http://images.backofthenet.info/loading.gif' /> Loading Message...");

	var xmlhttp = GetXMLHttpRequest('GET', url);

	// Set the callback function
	xmlhttp.onreadystatechange = function()
	{
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
		{
			//document.getElementById('message').innerHTML = xmlhttp.responseText;
			ShowPopup("View message", "", xmlhttp.responseText);
		}
		else {
			// waiting for the call to complete
		}
	};

	// Make the actual request
	xmlhttp.send(null);
}

/*function validateMessage(theForm)
{
	if (theForm.subject.value == '') {
		theForm.subject.focus();
		Alert('Please enter a subject');
		return false;
	}
	alert("poo");
	return true;
}*/

function ShowSendMessage(playerId, previousMessageId)
{
	var url = "/core_ajax.php?action=ShowSendMessage&Id="+playerId+"&pMessageId="+previousMessageId;

	ShowPopup("Send message", "", "<img src='http://images.backofthenet.info/loading.gif' /> Loading...");

	var xmlhttp = GetXMLHttpRequest('GET', url);

	// Set the callback function
	xmlhttp.onreadystatechange = function()
	{
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
		{
			ShowPopup("Send message", "", xmlhttp.responseText);
		}
		else {
			// waiting for the call to complete
		}
	};

	// Make the actual request
	xmlhttp.send(null);
}

function SendMessage(rId, subject, content, pMessageId)
{
	var url = "/core_ajax.php?action=SendMessage";
		
	ShowPopup("Send message", "", "<img src='http://images.backofthenet.info/loading.gif' /> Sending message...");

	var xmlhttp = GetXMLHttpRequest('POST', url);

	// Set the callback function
	xmlhttp.onreadystatechange = function()
	{
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
		{
			ShowPopup("Send message", "", xmlhttp.responseText);
			
			//opacity('generic_popup_title', 100, 0, 500);
			//document.getElementById('generic_popup').style.display='none';
			//changeOpac(100, 'generic_popup_title');
		}
		else {
			// waiting for the call to complete
		}
	};
 
	var params = "rId=" + encodeURI(rId) +
	             "&subject=" + encodeURI(subject) + 
	             "&content=" + encodeURI(content) + 
	             "&pMessageId=" + encodeURI(pMessageId);
	             
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", params.length);

	// Make the actual request
	xmlhttp.send(params);
}


function checkForNewShouts()
{
	var url = "/getupdates.php?action=shouts&data=" + lastShoutId;

	var xmlhttp = GetXMLHttpRequest('GET', url);

	// Set the callback function
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
		{
			// Output the results
			if (xmlhttp.responseText.length > 5)
			{
				var message = xmlhttp.responseText;
				var loc = message.indexOf(' ');
				if (loc != -1 && message.substr(0,loc) > lastShoutId)
				{
					lastShoutId = message.substr(0,loc);

					var divId = "shout" + lastShoutId;
					var shoutMessage = "<div id='" + divId + "'>" + message.substr(message.indexOf(' ')) + "</div>" + document.getElementById('messages').innerHTML;

					document.getElementById('messages').innerHTML = shoutMessage;

					//changeOpac(0, divId);
					//opacity(divId, 0, 100, 1000);
					//new Effect.Appear(divId);
					//new Effect.Grow(divId);

					//As we got a message, lets decrease the time between shout checks, make it more responsive
					if (shoutCheckTimeout > 15) { shoutCheckTimeout--; }
				}
			}
			else
			{
				//alert("no new messages");
				if (shoutCheckTimeout < 60) { shoutCheckTimeout++; }
			}
			setTimeout("checkForNewShouts(true)",shoutCheckTimeout*1000);

		}
		else {
			// waiting for the call to complete
		}
	};

	// Make the actual request
	xmlhttp.send(null);
}

function sendShout(obj)
{
	if (obj.value != '')
	{
		//var i = new Image();
		//var iurl = "http://" + window.location.host + "/shoutmessages.php?shoutboxmessage=" + obj.value;
		//i.src = iurl;
		
		var mid = "me_" + lastShoutId;
		
		obj.disabled = true;
		obj.readonly = true;
		
		var url = "/shoutmessages.php?shoutboxmessage=" + obj.value;

		var xmlhttp = GetXMLHttpRequest('GET', url);
		
		// Set the callback function
		xmlhttp.onreadystatechange = function()
		{
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
			{
				document.getElementById('post_'+mid).innerHTML = shoutPostString + obj.value;
				obj.value='';
				obj.disabled = false;
				obj.readonly = false;
			}
			else if(xmlhttp.readyState == 4)
			{
				obj.disabled = false;
				obj.readonly = false;
			}
			else {
				// waiting for the call to complete
				//obj.disabled = false;
				//document.getElementById('post_'+mid).innerHTML = shoutPostString + "Shout failed to send";
			}

			obj.focus();
		};

		var now = new Date();
		var hour = now.getHours();
		var minute = now.getMinutes();

		var ap = "am";
		if (hour   > 11) { ap = "pm";        }
		if (hour   > 12) { hour = hour - 12; }
		if (hour   == 0) { hour = 12;        }
		if (hour   < 10) { hour   = "0" + hour;   }
		if (minute < 10) { minute = "0" + minute; }

		//var firstbit = "<div id='"+mid+"'><font color='#a8a8a8'>[" + hour + ":" + minute + ap + "]</font><span id='post_"+mid+"'>"+shoutPostString+ obj.value+"</span></div>";
		var firstbit = "<div id='"+mid+"'><font color='#a8a8a8'>[" + hour + ":" + minute + ap + "]</font><span id='post_"+mid+"'>"+shoutPostString+"<img src='http://images.backofthenet.info/loading.gif' />  sending shout...</span></div>";
		document.getElementById('messages').innerHTML = firstbit + document.getElementById('messages').innerHTML;

		//changeOpac(0, mid);
		//opacity(mid, 0, 100, 1000);

		//new Effect.Appear(mid);
		//new Effect.Grow(mid);
		
		xmlhttp.send(null);
	}
}

var listHash = "";

function updateShoutUsers()
{
	var url = "/shoutusers.html";

	var xmlhttp = GetXMLHttpRequest('GET', url);

	// Set the callback function
	xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				  // Output the results
				  if (xmlhttp.responseText != "")
				  {

					var message = xmlhttp.responseText;
					if (xmlhttp.responseText.substr(0,xmlhttp.responseText.indexOf(' ')) != listHash)
					{
						listHash = xmlhttp.responseText.substr(0,xmlhttp.responseText.indexOf(' '));
						document.getElementById('shoutuserinfo').innerHTML = message.substr(message.indexOf(' '));
					}
				  }
				  else
				  {
					//alert("no new messages");
				  }
				  setTimeout("updateShoutUsers(true)",60000);

			} else {
					// waiting for the call to complete
			}
		};

	// Make the actual request
	xmlhttp.send(null);
}


function addHoverClass(element)
{
	element.onmouseover=function() {
		this.className+=" over";
	}
	element.onmouseout=function() {
		this.className=this.className.replace(" over", "");
	}
}


function checkForNewMessages()
{
	var url = "/getupdates.php?action=messages";/*&data=" + numMsgs;*/

	var xmlhttp = GetXMLHttpRequest('GET', url);

	// Set the callback function
	xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				  // Output the results
				  if (xmlhttp.responseText!= '' && parseInt(xmlhttp.responseText) > lastMsgNum)
				  {
					//alert('New private message arrived');
					lastMsgNum = parseInt(xmlhttp.responseText);
					//document.getElementById('messagemenuitem').innerHTML = "("+numMsgs+" new)";
					var ans = window.confirm("New message arrived, view message?");
					if (ans)
					{
						GetMessage(lastMsgNum);
					}
				  }
				  else
				  {
					//alert("no new messages");
				  }
				  setTimeout("checkForNewMessages()",90000);

			} else {
				// waiting for the call to complete
			}
		};

	// Make the actual request
	xmlhttp.send(null);

}




function checkForNewPrivateChat()
{
	var url = "http://" + window.location.host + "/privatechat.php?action=checkstatus";

	var xmlhttp = GetXMLHttpRequest('GET', url);

	// Set the callback function
	xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				  // Output the results
				  if (xmlhttp.responseText != "")
				  {
						var message = xmlhttp.responseText;
						var chatid  = xmlhttp.responseText.substr(0,xmlhttp.responseText.indexOf(' '));
						var abox = message.substr(message.indexOf(' '));
						if (confirm(abox))
						{
							window.open('privatechat.php?action=accept&requestid=' + chatid,'PrivateChat' + chatid,'width=330,height=290,resizable=no,scrollbars=no,toolbar=no,location=no,directories=no,status=no,menubar=no,copyhistory=no');
						}
						else
						{
							var i = new Image();
							var iurl = "http://" + window.location.host + "/privatechat.php?action=reject&chatid=" + chatid;
							i.src = iurl;
							alert(iurl);
						}
				  }
				  else
				  {
					//alert("no new chat");
				  }
				  setTimeout("checkForNewPrivateChat()",30000);

			} else {
					// waiting for the call to complete
			}
		};

	// Make the actual request
	xmlhttp.send(null);

}





function newwindow()
{
	window.open('http://live.xbox.com/en-GB/profile/Friends.aspx','jav','width=800,height=1000,scrollbars=yes');
}




function changeVis(HideId) {
	if (document.getElementById(HideId).style.display=='none') {
	   document.getElementById(HideId).style.display='block';
	}
	else {
	   document.getElementById(HideId).style.display='none';
	}
}


function confirmdelete()
{
	var ok = false;

	if (confirm('Are you sure you want to DELETE this item?') == true) {
		ok = true;
	}
	else {
		ok = false;
	}
	return ok;
}



function confirmAddGame(theForm)
{
	if (confirm('Are you sure you want to Add this game?') != true) {
		return false;
	}
	return true;
}



function checkResultsForm(theForm) {
	if (theForm.comments.value == '') {
		theForm.comments.focus();
		Alert('Please enter match commentary');
		return false;
	}
	Alert('test');
	return true;
}


//clears a textbox when it contains its default value ONLY
function clearBox(box) {
	 if(box.value==box.defaultValue) {
		 box.value = "";
	 }
}



function selectAll(formObj, checkB)
{
	isInverse = (checkB.checked) ? true : false;
	for (var i=0;i < formObj.length;i++)
	{
	  fldObj = formObj.elements[i];
	  if (fldObj.type == 'checkbox')
	  {
		 if(isInverse)
			fldObj.checked = (fldObj.checked) ? false : true;
		 else fldObj.checked = true;
	   }
	}
}

function SubmitRating(type, id, value, object)
{
	var url = "core_ajax.php?SubmitRating=" + type + "&id=" + id + "&value=" + value;

	var xmlhttp = GetXMLHttpRequest('GET', url);

	// Set the callback function
	xmlhttp.onreadystatechange = function() {
	if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
	{
		//alert(xmlhttp.responseText);

		//Now set the stars to what was retrieved;
		document.getElementById('current-rating').style.width = xmlhttp.responseText*25 + "px";
	}
	else {
		// waiting for the call to complete
	}
	};

	// Make the actual request
	xmlhttp.send(null);
}

function ShowSmileyDialog()
{
	content  = '<div style="text-align: center; margin: 0 auto;">';
	content  = '<a href="javascript:emoticon(\':twisted\')"><img src="http://images.backofthenet.info/shoutbox/smileys/twisted.gif" border="0"/></a> ';
	content += '<a href="javascript:emoticon(\':shock\')"><img src="http://images.backofthenet.info/shoutbox/smileys/eek.gif" border="0"/></a> ';
	content += '<a href="javascript:emoticon(\':evil\')"><img src="http://images.backofthenet.info/shoutbox/smileys/evil.gif" border="0"/></a> ';
	content += '<a href="javascript:emoticon(\':lol\')"><img src="http://images.backofthenet.info/shoutbox/smileys/lol.gif" border="0"/></a> ';
	content += '<a href="javascript:emoticon(\':mrgreen\')"><img src="http://images.backofthenet.info/shoutbox/smileys/mrgreen.gif" border="0"/></a> ';
	content += '<a href="javascript:emoticon(\':roll\')"><img src="http://images.backofthenet.info/shoutbox/smileys/rolleyes.gif" border="0"/></a> ';
	content += '<a href="javascript:emoticon(\':?\')"><img src="http://images.backofthenet.info/shoutbox/smileys/confused.gif" border="0"/></a> ';
	content += '<a href="javascript:emoticon(\':D\')"><img src="http://images.backofthenet.info/shoutbox/smileys/biggrin.gif" border="0"/></a> ';
	content += '<a href="javascript:emoticon(\'8)\')"><img src="http://images.backofthenet.info/shoutbox/smileys/cool.gif" border="0"/></a> ';
	content += '<a href="javascript:emoticon(\':x\')"><img src="http://images.backofthenet.info/shoutbox/smileys/mad.gif" border="0"/></a> ';
	content += '<a href="javascript:emoticon(\':|\')"><img src="http://images.backofthenet.info/shoutbox/smileys/neutral.gif" border="0"/> ';
	content += '<a href="javascript:emoticon(\':P\')"><img src="http://images.backofthenet.info/shoutbox/smileys/razz.gif" border="0"/> ';
	content += '<a href="javascript:emoticon(\':(\')"><img src="http://images.backofthenet.info/shoutbox/smileys/sad.gif" border="0"/></a> ';
	content += '<a href="javascript:emoticon(\':)\')"><img src="http://images.backofthenet.info/shoutbox/smileys/smile.gif" border="0"/></a> ';
	content += '<a href="javascript:emoticon(\':o\')"><img src="http://images.backofthenet.info/shoutbox/smileys/surprised.gif" border="0"/></a> ';
	content += '<a href="javascript:emoticon(\';)\')"><img src="http://images.backofthenet.info/shoutbox/smileys/wink.gif" border="0"/></a> ';
	content += '<br /><a href="http://www.easyfreesmileys.com" target="_blank">Get more smileys</a>';
	content += '<br /><a href="http://www.smileyshut.com/make-a-smiley.html" target="_blank">Make a smiley</a>';
	content += '</div>';

	ShowPopup("Select Smileys", "Select Smileys", content)
}


function ShowPopup(title, summary, content)
{
	document.getElementById('generic_popup_title').innerHTML   = title;
	document.getElementById('generic_popup_summary').innerHTML = summary;
	document.getElementById('generic_popup_content').innerHTML = content;
	
	document.getElementById('generic_popup').style.display='block';
}

