// @name      The Fade Anything Technique
// @namespace http://www.axentric.com/aside/fat/
// @version   1.0-RC1
// @author    Adam Michela

var Fat = {
	make_hex : function (r,g,b) 
	{
		r = r.toString(16); if (r.length == 1) r = '0' + r;
		g = g.toString(16); if (g.length == 1) g = '0' + g;
		b = b.toString(16); if (b.length == 1) b = '0' + b;
		return "#" + r + g + b;
	},
	fade_all : function ()
	{
		var a = document.getElementsByTagName("*");
		for (var i = 0; i < a.length; i++) 
		{
			var o = a[i];
			var r = /fade-?(\w{3,6})?/.exec(o.className);
			if (r)
			{
				if (!r[1]) r[1] = "";
				if (o.id) Fat.fade_element(o.id,null,null,"#"+r[1]);
			}
		}
	},
	fade_element : function (id, fps, duration, from, to) 
	{
		if (!fps) fps = 30;
		if (!duration) duration = 3000;
		if (!from || from=="#") from = "#FFFF33";
		if (!to) to = this.get_bgcolor(id);
		
		var frames = Math.round(fps * (duration / 1000));
		var interval = duration / frames;
		var delay = interval;
		var frame = 0;
		
		if (from.length < 7) from += from.substr(1,3);
		if (to.length < 7) to += to.substr(1,3);
		
		var rf = parseInt(from.substr(1,2),16);
		var gf = parseInt(from.substr(3,2),16);
		var bf = parseInt(from.substr(5,2),16);
		var rt = parseInt(to.substr(1,2),16);
		var gt = parseInt(to.substr(3,2),16);
		var bt = parseInt(to.substr(5,2),16);
		
		var r,g,b,h;
		while (frame < frames)
		{
			r = Math.floor(rf * ((frames-frame)/frames) + rt * (frame/frames));
			g = Math.floor(gf * ((frames-frame)/frames) + gt * (frame/frames));
			b = Math.floor(bf * ((frames-frame)/frames) + bt * (frame/frames));
			h = this.make_hex(r,g,b);
		
			setTimeout("Fat.set_bgcolor('"+id+"','"+h+"')", delay);

			frame++;
			delay = interval * frame; 
		}
		setTimeout("Fat.set_bgcolor('"+id+"','"+to+"')", delay);
	},
	set_bgcolor : function (id, c)
	{
		var o = document.getElementById(id);
		o.style.backgroundColor = c;
	},
	get_bgcolor : function (id)
	{
		var o = document.getElementById(id);
		while(o)
		{
			var c;
			if (window.getComputedStyle) c = window.getComputedStyle(o,null).getPropertyValue("background-color");
			if (o.currentStyle) c = o.currentStyle.backgroundColor;
			if ((c != "" && c != "transparent") || o.tagName == "BODY") { break; }
			o = o.parentNode;
		}
		if (c == undefined || c == "" || c == "transparent") c = "#FFFFFF";
		var rgb = c.match(/rgb\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)/);
		if (rgb) c = this.make_hex(parseInt(rgb[1]),parseInt(rgb[2]),parseInt(rgb[3]));
		return c;
	}
}

// Based in the  XHTML live Chat (http://www.plasticshore.com)
// This script is published under a creative commons license
// license: http://creativecommons.org/licenses/by-nc-sa/2.0/
var current_class = 'row2';
var counter = 0;
var refresh_time = 4000;
var sendTimeout, receiveTimeout, cssRules, row1_color, row2_color;
var online = true;
// time
var now = new Date();
var time = Math.round(now.getTime()/1000);

var lastID = -1; //initial value will be replaced by the latest known id
window.onload = initJavaScript;

// Initiates the two objects for sending and receiving data
var httpReceiveChat = getHTTPObject();
var httpSendChat = getHTTPObject();

// Sound switch
var play_sound = false;
function sound_on()
{
	play_sound = true;
	document.getElementById('reload').style.border = '5px solid #FFFF00';
}
function sound_off()
{
	play_sound = false;
	document.getElementById('reload').style.border = '';
}
window.onblur = sound_on;
window.onfocus = sound_off;

function Time() {
	now = new Date();
	return Math.round(now.getTime()/1000);
}

function resetTime() {
	time = Time();
	refresh_time = 4000;
}

function initJavaScript() 
{
	if(document.forms['chatForm'])
	{
		document.forms['chatForm'].elements['chatbarText'].setAttribute('autocomplete','off'); //this non standard attribute prevents firefox' autofill function to clash with this script
		checkStatus(''); //sets the initial value and state of the input comment
	}
	get_colors();
	receiveChatText(); //initiates the first data query

	// Get background colors from classes
	if (!document.styleSheets) 
	{
		return;
	}
}

// Get the background colors from css classes
function get_colors()
{
	var prefix;
	var theRules = new Array();
	if (document.styleSheets[0].cssRules)
	{
		theRules = document.styleSheets[0].cssRules
		prefix = 'td.';
	}
	else if (document.styleSheets[0].rules)
	{
		theRules = document.styleSheets[0].rules
		prefix = 'TD.';
	}

	for (x=0;x<theRules.length; x++)
	{
		if(theRules[x].selectorText == (prefix+'row1'))
		{
			row1_color = theRules[x].style['backgroundColor'];
		}
		else if (theRules[x].selectorText == (prefix+'row2'))
		{
			row2_color = theRules[x].style['backgroundColor'];
		}
	}
}

// Timeout Prevention
function ajaxTimeout(obj)
{
  var xhr;	

	// Wich Object timeout?
	if (obj == 1)
	{
		xhr = httpReceiveChat;
	}
	else
	{
	 xhr = httpSendChat;
	}
	
	// Abort it to try again later
	xhr.abort();
}

// Initiates the first data query
function receiveChatText()
{
	if (httpReceiveChat.readyState == 4 || httpReceiveChat.readyState == 0) 
	{
		var param = 'lastID='+lastID+'&act=read&rand='+Math.floor(Math.random() * 1000000);
		// online status
		if ( online )
		{
			param = param+'&online=true';
			online = false;
			setTimeout("online = true;", (refresh_time*10));
		}
		httpReceiveChat.open("POST",ChatActionurl, true);
		httpReceiveChat.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		httpReceiveChat.onreadystatechange = handlehHttpReceiveChat; 
		// Timeout Prevention
		receiveTimeout = setTimeout("ajaxTimeout(1);", (refresh_time/2));
	  	httpReceiveChat.send(param);
	}
}

//deals with the servers' reply to requesting new content
function handlehHttpReceiveChat() {
	if (httpReceiveChat.readyState == 4) {
		// We didn't timeout 
		clearTimeout(receiveTimeout);
		results = httpReceiveChat.responseText.split('---'); //the fields are seperated by ---
		//alert(results);
		if (results.length > 2) {
			// Check that the last message wasn't printed before.
			if (lastID < results[results.length-5]) {
				// Goes through the result one message at a time
				for (i=0;i < (results.length-1);i=i+5) { 
					// Insert the new content into the page
					if (lastID < results[i+1]) {
						insertNewContent(results[i+2],results[i+3],results[i+4] ,lastID); 
						resetTime();
					}
				}
				lastID = results[results.length-5];
			}
		}
		else {
			// no new comment since..
			// 60 seconds
			if ( refresh_time == 4000 & ((time + 60) < Time()) ) {
				// set refresh to 10 seconds
				refresh_time = 10000;
			}
			// 5 minutes
			else if ( refresh_time == 10000 & ((time + 300) < Time()) ) {
				// set refresh to 30 seconds
				refresh_time = 30000;
			}
			// 30 minutes
			else if ( refresh_time == 30000 & ((time + 1800) < Time()) ) {
				// set refresh to 2 minutes
				refresh_time = 120000;
			}
			// 60 minutes
			else if ( refresh_time == 120000 & ((time + 3600) < Time()) ) {
				// set refresh to 5 minutes
				refresh_time = 300000;
			}
		}
		setTimeout('receiveChatText();', refresh_time);
	}
}

// Lets put the shouts to the table
function insertNewContent(liName, liText, liTime, last_id)
{
	// Row Id
	var id = 'row_'+counter;

  // Get a reference to the table
  var tableRef = document.getElementById("outputList");

  // Insert a row in the table at row index 0
  var newRow   = tableRef.insertRow(0);

	// Put some attributes to the row
	newRow.setAttribute('id', id);
	
	if(current_class == "row2")
	{
		newRow.style.backgroundColor = row1_color;
	}
	else
	{
		newRow.style.backgroundColor = row2_color;
	}

  // Insert 2 cells in the row
  var newCell  = newRow.insertCell(0);
	var newCell2  = newRow.insertCell(1);
	
	// Put some attributes to the rows
	newCell.setAttribute('width', 110);

  // Append a text node to the cell
	newCell.innerHTML = '<span class="name"><b>'+liName+'</b><br /><i>'+liTime+'</i></span>';   
	newCell2.innerHTML = '<span class="postbody" style="width: 510px; overflow: hidden;">'+liText+'</span>';

	// Add 1 to counter
	counter++;

	// Fade effect
	// We don't want to fade the first pack of messages 
	if(last_id != -1)
	{
		Fat.fade_element(id, 30, 2000, '#666666','#D9D9D9');
		// Finally we can set the cells classes after the fade
		setTimeout("classChanger('"+newRow.id+"');", 2006);
		// play sound
		if ( play_sound == true )
		{
			if (navigator.appName.indexOf ("Microsoft") !=-1)
			{
				document.getElementById("chatsound").Play();
				setTimeout('document.getElementById("chatsound").Play();', 1500);
			}
			else
			{
				document.embeds[0].Play();
				setTimeout('document.embeds[0].Play();', 1500);
			}
		}
		return true;
	}
	// Finally we can set the cells classes after the fade
	classChanger(newRow.id);
}

function classChanger(obj_id)
{
	var obj = document.getElementById(obj_id);
	obj.childNodes[0].className = current_class;
	obj.childNodes[1].className = current_class;
	
	if(current_class == "row2")
	{
		current_class = "row1";
	}
	else
	{
		current_class = "row2";
	}
}

//stores a new comment on the server
function sendComment() 
{
	setTimeout("document.forms['chatForm'].submit.disabled = true;", 0);
	setTimeout("document.forms['chatForm'].submit.disabled = false;", refresh_time);
	//currentChatText = encodeURIComponent(document.forms['chatForm'].elements['chatbarText'].value);
	currentChatText = escape(document.forms['chatForm'].elements['chatbarText'].value);
	if (currentChatText != '' & (httpSendChat.readyState == 4 || httpSendChat.readyState == 0))
	{
		param = 'act=add&message='+ currentChatText;
		httpSendChat.open("POST", ChatActionurl, true);
		httpSendChat.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		httpSendChat.onreadystatechange = handlehHttpSendChat;
		// Timeout Prevention
		sendTimeout = setTimeout("ajaxTimeout(2);", (refresh_time/2));
		httpSendChat.send(param);
		document.forms['chatForm'].elements['chatbarText'].value = '';
		document.forms['chatForm'].elements['chatbarText'].focus();
	}
	sound_off();
}

//deals with the servers' reply to sending a comment
function handlehHttpSendChat()
{
	if (httpSendChat.readyState == 4)
	{
		// We didn't timeout
		clearTimeout(sendTimeout);
		setTimeout("receiveChatText();", (refresh_time/2)); //refreshes the chat after a new comment has been added (this makes it more responsive)
		var error_status = httpSendChat.responseText.split('---')[2];
		if(error_status == 1)
		{
			alert(httpSendChat.responseText.split('---')[1]);
			setTimeout("sound_off();", 100);
		}
	}
}

//does clever things to the input and submit
function checkStatus(focusState)
{
	currentChatText = document.forms['chatForm'].elements['chatbarText'];
	oSubmit = document.forms['chatForm'].elements['submit'];
	if (currentChatText.value != '' || focusState == 'active')
	{
		oSubmit.disabled = false;
	} 
	else 
	{
		oSubmit.disabled = true;
	}
}


//initiates the XMLHttpRequest object
//as found here: http://www.webpasties.com/xmlHttpRequest
function getHTTPObject()
{
  var xmlhttp;
  /*@cc_on
  @if (@_jscript_version >= 5)
    try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        xmlhttp = false;
      }
    }
  @else
  xmlhttp = false;
  @end @*/
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined')
	{
    try
		{
      xmlhttp = new XMLHttpRequest();
    }
		catch (e)
		{
      xmlhttp = false;
    }
  }
  return xmlhttp;
}

function quoteSelection()
{
	theSelection = false;
	if (document.getSelection)
	{
		theSelection = document.getSelection();
	}
	else if (document.selection)
	{
		theSelection = document.selection.createRange().text;
	}

	if (theSelection)
	{
		// Add tags around selection
		emoticon( '[quote]' + theSelection + '[/quote]\n');
		document.forms['chatForm'].elements['chatbarText'].focus();
		theSelection = '';
		return;
	}
	else
	{
		alert(no_text_selected);
		setTimeout("sound_off();", 100);
	}
}

function storeCaret(textEl)
{
	if (textEl.createTextRange) textEl.caretPos = document.selection.createRange().duplicate();
}

function emoticon(text)
{
	if (document.forms['chatForm'].elements['chatbarText'].createTextRange && document.forms['chatForm'].elements['chatbarText'].caretPos)
	{
		var caretPos = document.forms['chatForm'].elements['chatbarText'].caretPos;
		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text + ' ' : text;
		document.forms['chatForm'].elements['chatbarText'].focus();
	}
	else
	{
		document.forms['chatForm'].elements['chatbarText'].value  += text;
		document.forms['chatForm'].elements['chatbarText'].focus();
	}
}

function checkForm()
{
	if (document.forms['chatForm'].elements['chatbarText'].value.length < 2)
	{
		alert(empty_message);
		setTimeout("sound_off();", 100);
		return false;
	}
}

function resize(img)
{
	if (img.width > screen.width-400)
	{
		img.width = (screen.width-400);
	}
}
