/* YetAnotherShoutBox AJAX Javascript

 * author: Thomas Lorenz

 * Version: 1.1.1

 * http://www.freudeamgolfen.de

 */



//define the local vars

var YaSBLoadTimes = 1;

var YaSBGetUrl = "";

var YaSBSendUrl = "";

var httpReceiveChat = getHTTPObject();

var httpSendChat = getHTTPObject();

var YaSBSound = false;

var YaSBto = 0;

var YaSBsmilyWindow;



//define the date which will be used for requests

theDate = new Date();

var expiryDate = new Date( theDate.getTime() + 5184000000 ).toGMTString();



//setup onload function

if(typeof window.addEventListener != 'undefined'){	//.. gecko, safari, konqueror and standard

	window.addEventListener('load', initYaSB, false);

}

else if(typeof document.addEventListener != 'undefined'){	//.. opera 7

	document.addEventListener('load', initYaSB, false);

}

else if(typeof window.attachEvent != 'undefined'){	//.. win/ie

	window.attachEvent('onload', initYaSB);

}



/**

 * Init the YaSB AJAX Scripts

 */

function initYaSB() {

	if (!document.getElementById('yasbText')) { return; }

	document.getElementById('yasbText').setAttribute('autocomplete','off'); //this non standard attribute prevents firefox' autofill function to clash with this script

	if(document.getElementById('yasbCheck')){

		document.getElementById('yasbCheck').setAttribute('autocomplete','off');

	}

	// initiate the vars that have not been initiated

	yasbSound =  YaSBgetCookie("yasbSound")==1; //No sound by default

	YaSBGetUrl = YaSBroot + "index.php?yasbtask=getshouts";

	YaSBSendUrl = YaSBroot + "index.php?yasbtask=addshout";

	YaSBto = YaSBrefresh;

	

	document.getElementById('yasbName').onblur = YaSBcheckName;

	document.getElementById('yasbSubmit').onclick = YaSBsendShout;

    document.getElementById('yasbChatForm').onsubmit = function () { return false; }

	// When user mouses over shoutbox

    document.getElementById('chatoutput').onmouseover = function () {

    	if (YaSBLoadTimes > 9) {

    		YaSBLoadTimes = 1;

			YaSBquery();

    	}

    	YaSBto = YaSBrefresh;

    }

	

    YaSBreloadCaptcha();

	YaSBcheckName(); //checks the initial value of the input name

	setTimeout('YaSBquery()', YaSBto); //initiates the first data query

}



/**

 * Query the server for new messages

 */

function YaSBquery() {

	latest = parseInt(document.getElementById('yasbID').value);

	if (httpReceiveChat.readyState == 4 || httpReceiveChat.readyState == 0) {

  		httpReceiveChat.open("GET",YaSBGetUrl + '&yasbID=' + latest + '&rand='+Math.floor(Math.random() * 1000000), true);

		httpReceiveChat.onreadystatechange = YaSBHandleChatRecive; 

  		httpReceiveChat.send(null);

		YaSBLoadTimes++;

	    if (YaSBLoadTimes > 9) YaSBto = YaSBto * 5 / 4;

	}

    setTimeout('YaSBquery()',YaSBto);

}



/**

 * Handle the AJAX server answer when recieveing new shouts

 */

function YaSBHandleChatRecive() {

	if (httpReceiveChat.readyState == 4) {

		results = httpReceiveChat.responseText.split('----'); 

		if (results.length >= 5) {

			for(i=0;i < (results.length-1);i=i+5) {

				YaSBInsertShout(results[i+1], results[i+2], results[i+3] , results[i+4]);

				document.getElementById('yasbID').value = parseInt(results[i]);

				document.getElementById('yasbTime').value = parseInt(results[i+4]);

			}

			YaSBto = YaSBrefresh;

			YaSBLoadTimes = 1;

			YaSBnotify();

		}

		YaSBUpdateLatestPost();

	}

}



/**

 * Insert a new shout at the begin of the list

 * @param uid the user id of the poster

 * @param Name the poster's name

 * @param Text the text

 * @param Time the timestamp the post has been send

 */

function YaSBInsertShout(uid,name,text, time) {

	insertO = document.getElementById("outputList");

	oLi = document.createElement('li');

	oSpan = document.createElement('span');

	oSpan.setAttribute('class','uname');

	oSpan.setAttribute('title',YaSBstrftime(time));

	

	oName = document.createTextNode(name);

	

	if (uid != 0) {

		oURL = document.createElement('a');

		oURL.href = 'index.php?option=com_comprofiler&task=userProfile&user='+uid;

		oURL.appendChild(oName);

	} else {

		oURL = oName;

	}

	

	oSpan.appendChild(oURL);

	oSpan.appendChild(document.createTextNode(' : '));

	oLi.appendChild(oSpan);

	oLi.innerHTML += text;

	insertO.insertBefore(oLi, insertO.firstChild);

}



/**

 * Format a Unix timestamp into human readable string

 * @param time Unix time stamp

 * @return String the human readable time

 */

function YaSBstrftime(time){

	myDate = new Date(time * 1000);

	ret = '';

	if( myDate.getDate().toString().length < 2 ){

		ret = ret + '0' + myDate.getDate().toString() + '.';

	}else{

		ret = ret + myDate.getDate().toString() + '.';

	}

	if( (myDate.getMonth()+1).toString().length < 2 ){

		ret = ret + '0' + (myDate.getMonth()+1).toString() + '.';

	}else{

		ret = ret + (myDate.getMonth()+1).toString() + '.';

	}

	ret = ret + myDate.getFullYear().toString().substring(2);

	ret = ret + ' - ';

	if( myDate.getHours().toString().length < 2 ){

		ret = ret + '0' + myDate.getHours().toString() + ':';

	}else{

		ret = ret + myDate.getHours().toString() + ':';

	}

	if( myDate.getMinutes().toString().length < 2 ){

		ret = ret + '0' + myDate.getMinutes().toString();

	}else{

		ret = ret + myDate.getMinutes().toString();

	}

	return ret;

}



/**

 * Update the time displayes in the top of the shoutbox.

 * @return void

 */

function YaSBUpdateLatestPost(){

	//Get the time in seconds the last post is away

	now = new Date();

	last = parseInt(document.getElementById('yasbTime').value)-10;

	timeSince = Math.floor((now.getTime()/1000)-last);

	if(timeSince<0){

		timeSince = 0;

	}



	//figure out the first component of the strings

	for(i = 0;i < YaSBlanTime.length; i++){

		val = parseInt(YaSBlanTime[i][0]);

		name = YaSBlanTime[i][1];

		names = YaSBlanTime[i][2];

		count = Math.floor(timeSince/val);

		if(count > 0){

			break;

		}

	}



	retStr = (count==1)?('1 '+name):(count.toString()+' '+names);

	//the second part

	if( i+1 < YaSBlanTime.length ){

		val2 = parseInt(YaSBlanTime[i+1][0]);

		name2 = YaSBlanTime[i+1][1];

		names2 = YaSBlanTime[i+1][2];

		count2 = Math.floor((timeSince-(val*count))/val2);

		if(count2 > 0){

			retStr = retStr + ', ' + ( (count2==1) ? ('1 '+name2) : (count2.toString()+' '+names2) );

		}

	}

		

	retStr = retStr + ' ' + YaSBlanTimeSince;

	

	response = document.getElementById("responseTime");

	response.innerHTML = retStr;

}



/**

 * Play the sound applet if it is to find

 * @return void

 */

function YaSBnotify(){

	media = document.getElementById('yasbMedia');

	if (Boolean(media) && YaSBSound && navigator.javaEnabled()){

		media.play();

	}

}



/**

 * Parse the user entered values and send the shout to the server

 * @return void

 */

function YaSBsendShout() {

	if(document.images.captImg){

		if(document.forms['yasbChatForm'].elements['yasbCheck'].value == ''){

			alert(YaSBlanCaptWarning);

			return;

		}

	}



	currentChatText = document.getElementById('yasbText').value;

	if (currentChatText == ''){ return; }

	if (httpSendChat.readyState == 4 || httpSendChat.readyState == 0) {

		currentName = document.getElementById('yasbName').value;

		param = 'yasbName='+ encodeURIComponent(currentName)+'&yasbText='+ encodeURIComponent(currentChatText);

		if(document.images.captImg){

			param = param + '&yasbCode='  + document.getElementById('yasbCode').value;

			param = param + '&yasbCheck=' + document.getElementById('yasbCheck').value;

		}

		httpSendChat.open("POST", YaSBSendUrl, true);

		httpSendChat.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

		httpSendChat.onreadystatechange = YaSBHandleSendChat;

		httpSendChat.send(param);

	}

	YaSBcheckName();

}



/**

 * Handle the server's answer when sending a shout

 * @return void

 */

function YaSBHandleSendChat(){

	if (httpSendChat.readyState == 4) {

		error = httpSendChat.responseText;

		if(error != ''){

			if( document.getElementById("chatError") ){

				document.getElementById("chatError").innerHTML = error;

			}else{

				pElem = document.createElement('p');

				pElem.setAttribute('id', 'chatError');

				pElem.innerHTML = error;

				document.getElementById('yasbChatForm').insertBefore(

						pElem,

						document.getElementById('yasbChatForm').firstChild);

			}

		}else{

			if(document.getElementById('chatError')){

				document.getElementById('yasbChatForm').removeChild(

						document.getElementById('chatError'));

			}

		}

		document.getElementById('yasbText').value = '';

		YaSBreloadCaptcha();

		YaSBquery();

	}

}



/**

 * Reload the Captcha image with a new value if the image tag exists

 * @return void

 */

function YaSBreloadCaptcha(){

	if(!document.images.captImg){return;}

	code = Math.floor(Math.random()*511)+2;

	img = YaSBbase + "media/captcha.php?code=" + code;

	img = img + "&d=" + Math.floor(Math.random()*10000);

	document.images.captImg.src = img;

	document.getElementById('yasbCode').value = code;

	document.getElementById('yasbCheck').value = '';

}



/**

 * Switch sound notifications on or off depending on the current state

 * @return void

 */

function YaSBtoggleSound(){

	//get the new sound prederences

	YaSBSound = (YaSBgetCookie("yasbSound")!=1);

	if( YaSBSound ){

		if(navigator.javaEnabled()){

			document.cookie = "yasbSound=1;expires="+expiryDate+";path=/;";

			document.getElementById('yasbSoundSwitch').src = YaSBbase+"media/sound_1.gif";

			document.getElementById('yasbMediaCnt').innerHTML = '<applet code="SoundPlayer.class" codebase="'+YaSBbase+'media/" id="yasbMedia" width="0" height="0">'+

				'<param name="SoundFileName" value="'+YaSBbase+'media/msg.wav" />'+

				'</applet>';

		}else{

			alert(YaSBlanJavaWarning);

			document.getElementById('yasbSoundSwitch').src = YaSBbase+"media/sound_0.gif";

		}

	}else{

		document.cookie = "yasbSound=0;expires="+expiryDate+";path=/;";

		document.getElementById('yasbSoundSwitch').src = YaSBbase+"media/sound_0.gif";

		container = document.getElementById('yasbMediaCnt');

		while(container.hasChildNodes()){

			container.removeChild(container.firstChild);

		}

	}

}



/**

 * Guess the Name of the shouter, if a user enters an own name, use that

 * @return void

 */

function YaSBcheckName() {

	

	nameCookie = YaSBgetCookie('yasbName');

	nameField = document.getElementById('yasbName');

		

	if (nameCookie && nameField.value == '') {

		nameField.value = nameCookie;

		return;

	}

	

	if (nameField.value == '') {

		nameField.value = 'Visitante_'+ Math.floor((Math.random() * 9000) + 1000);

	}

	

	if (nameField.value != nameCookie) {

		document.cookie = "yasbName="+nameField.value+";expires="+expiryDate+";path=/";

	}

}



/**

 * Handle the pessed enter event in the text or captcha field

 * @param field a reference to the field

 * @param event the event stranmitted

 * @return boolen true if nothing was done

 */

function YaSBEnter(field,event) {

	var theCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;

	if (theCode == 13) {

		//Enter was pressed

		if( document.images.captImg ){

			if(document.getElementById('yasbCheck').value == ''){

				document.getElementById('yasbCheck').focus();

				return false;

			}else if(document.getElementById('yasbText').value == ''){

				document.getElementById('yasbText').focus();

				return false;

			}else{

				YaSBsendShout();

				return false;

			}

		}else{

			YaSBsendShout();

			return false;

		}

	} 

	else return true;

}



/**

 * Return the value of the cookie with the name 'name'

 * @param name string the cookie's name

 * @return string the cookie's value

 */

function YaSBgetCookie(name) {

	var dc = document.cookie;

	var prefix = name + "=";

	var begin = dc.indexOf("; " + prefix);

	if (begin == -1) {

		begin = dc.indexOf(prefix);

		if (begin != 0) return null;

	}else{

	    begin += 2;

	}

	var end = document.cookie.indexOf(";", begin);

	if (end == -1){

		end = dc.length;

	}

	return unescape(dc.substring(begin + prefix.length, end));

}



function YaSBSmilies(){

	if(!YaSBsmilyList){return;}



	if (YaSBsmilyWindow){

		YaSBsmilyWindow.close();

	}

	YaSBsmilyWindow = window.open("", "add_smileys", "toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,width=500,height=600,resizable=yes,dependent=yes");

	YaSBsmilyWindow.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n<html>');

	YaSBsmilyWindow.document.write('\n\t<head>\n\t\t<title>Emoticons</title>\n\t\t <style>\n\t\t.tborder\n\t\t\t{\n\t\t\t\t\tborder-top: solid  1px #454545;\n\t\t\t\t\tborder-left: solid 1px #454545;\n\t\t\t\t\tborder-right: solid  1px black;\n\t\t\t\t\tborder-bottom: solid 1px black;\n\t\t\t\t\tbackground-color: #ffffff;\n\t\t\t\t\tpadding: 0px;\n\t\t\t\t\tborder-collapse:collapse;\n\t\t\t}\n\t\tbody\n\t\t\t{\n\t\t\t\t\tbackground-color: #cccccc;\n\t\t\t\t\tmargin: 0px;\n\t\t\t\t\tpadding: 5px 20px 5px 20px;\n\t\t\t}\n\t\tbody, td\n\t\t\t{\n\t\t\t\t\tcolor: #ffffff;\n\t\t\t\t\tfont-size: small;\n\t\t\t\t\tfont-family: tahoma, helvetica, serif;\n\t\t\t}\n\t\t.titlebg, tr.titlebg td\n\t\t\t{\n\t\t\t\t\tbackground-color: #333333;\n\t\t\t\t\tfont-weight: bold;\n\t\t\t\t\tcolor: #eeeeee;\n\t\t\t\t\tfont-style: normal;\n\t\t\t}\n\t\t.windowbg\n\t\t\t{\n\t\t\t\t\tfont-family: tahoma, helvetica, serif;\n\t\t\t\t\tcolor: #ffffff;\n\t\t\t\t\tbackground-color: #eeeeee;\n\t\t\t\t\tborder-top: solid  1px #606060;\n\t\t\t\t\tborder-left: solid 1px #606060;\n\t\t\t\t\tborder-right: solid  1px black;\n\t\t\t\t\tborder-bottom: solid 1px black;\n\t\t\t}\n\t\t</style> \n\t</head>');

	YaSBsmilyWindow.document.write('\n\t<body style="margin: 1ex;">\n\t\t<table width="100%" cellpadding="5" cellspacing="0" border="0" class="tborder">\n\t\t\t<tr class="titlebg"><td align="left">'+YaSBlanChoose+'</td></tr>\n\t\t\t<tr class="windowbg"><td align="left">');



	for (i = 0; i < YaSBsmilyList.length; i++)

	{

		YaSBsmilyList[i][2] = YaSBsmilyList[i][0].replace(/"/g, '&quot;');

		YaSBsmilyWindow.document.write('<a href="javascript:void(0);" onclick="window.opener.YaSBinsrtSmily(&quot; ' + YaSBsmilyList[i][0] + '&quot;); window.focus(); return false;"><img src="' + YaSBbase + 'smilies/' + YaSBsmilyList[i][1] + '" alt="' + YaSBsmilyList[i][2] + '" title="' + YaSBsmilyList[i][2] + '" style="padding: 4px;" border="0" /></a> ');

	}

	YaSBsmilyWindow.document.write("<br />");



	YaSBsmilyWindow.document.write('</td></tr>\n\t\t\t<tr><td align="center" class="windowbg"><a href="javascript:window.close();\">'+YaSBlanClose+'</a></td></tr>\n\t\t</table>\n\t</body>\n</html>');

	YaSBsmilyWindow.document.close();

	YaSBsmilyWindow.focus();	

}



function YaSBinsrtSmily(smily){

	textarea = document.getElementById('yasbText');

	if(!textarea){return;}

	if (typeof(textarea.caretPos) != "undefined" && textarea.createTextRange){// Attempt to create a text range (IE).

		var caretPos = textarea.caretPos;

		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? smily + ' ' : smily;

		caretPos.select();

	}

	

	else if (typeof(textarea.selectionStart) != "undefined"){// Mozilla text range replace.

		var begin = textarea.value.substr(0, textarea.selectionStart);

		var end = textarea.value.substr(textarea.selectionEnd);

		var scrollPos = textarea.scrollTop;



		textarea.value = begin + smily + end;

		if (textarea.setSelectionRange){

			textarea.focus();

			textarea.setSelectionRange(begin.length + smily.length, begin.length + smily.length);

		}

		textarea.scrollTop = scrollPos;

	}else{// Just put it on the end.

		textarea.value += text;

		textarea.focus(textarea.value.length - 1);

	}

}



/**

 * Switch the visibiliy of the help content on or off depending on the current settings

 * @param obj the parant element of the ToggleHelp

 * @return void

 */

function YaSBtoggleHelp(obj){

	if(obj.getElementById('bbHelpContent').style.display=='none'){

		obj.getElementById('bbHelpContent').style.display='';

	}else{

		obj.getElementById('bbHelpContent').style.display='none';

	}

}



function YaSBbbCode(code){

	textarea = document.getElementById('yasbText');

	if(!textarea){return}

	colDef = false;

	if(code.indexOf('=') > -1){

		code = code.substring(0, code.indexOf('=') );

		colDef = true;

	}



	if (typeof(document.selection) != "undefined"){// Attempt to create a text range (IE).

		textarea.focus ();

		start = -document.selection.createRange().text.length;

		Sel = document.selection.createRange ();

		Sel.moveStart ('character', -textarea.value.length);

		stop = Sel.text.length;

		start += stop;

		text = textarea.value;

		textarea.value = text.substring(0, start) + "["+code+(colDef?"=":"")+"]"+

					text.substring(start,stop) + "[/" + code+ "]"+

					text.substring(stop);

		range = textarea.createTextRange();

		if(colDef || start==stop){

			CPos = start + 2 + code.length;

		}else{

			CPos = start + 7 + 2*code.length;

		}

		range.collapse(true);

		range.moveEnd('character', CPos);

		range.moveStart('character', CPos);

		range.select();

	}else if (typeof(textarea.selectionStart) != "undefined"){// Mozilla text range replace.

		selStart = textarea.selectionStart;

		selStop = textarea.selectionEnd;

		begin = textarea.value.substring(0, selStart);

		middle = textarea.value.substring(selStart,selStop);

		end = textarea.value.substring(selStop);

		scrollPos = textarea.scrollTop;

		textarea.value = begin + "[" + code;

		if(colDef){textarea.value = textarea.value + "=";}

		textarea.value = textarea.value  + "]" + middle + "[/" + code + "]" + end;

		textarea.scrollTop = scrollPos;

		textarea.focus();

		if(colDef || middle.length == 0){

			CPos = selStart + 2 + code.length

		}else{

			CPos = selStop + 5 + 2 * code.length

		}

		textarea.setSelectionRange(CPos,CPos);

	}else{// Just put it on the end.

		textarea.value += "[" + code + (colDef?'=':'') + "][/" + code + "]";

		textarea.focus();

	}

}



/**

 * Returns an XMLHttpRequestObject

 * @return XMLHttpRequest

 */

//as found here: http://www.webpasties.com/xmlHttpRequest

function getHTTPObject() {

	var xmlHttp = null;

	// Mozilla, Opera, Safari sowie Internet Explorer (ab v7)

	if (typeof XMLHttpRequest != 'undefined') {

	    xmlHttp = new XMLHttpRequest();

	}

	if (!xmlHttp) {

	    // Internet Explorer 6 und älter

	    try {

	        xmlHttp  = new ActiveXObject("Msxml2.XMLHTTP");

	    } catch(e) {

	        try {

	            xmlHttp  = new ActiveXObject("Microsoft.XMLHTTP");

	        } catch(e) {

	            xmlHttp  = false;

	        }

	    }

	}

	return xmlHttp;

}
