/*****
http://www.byoaudio.com/
Always do obfuscation before releasing to public!
http://en.wikipedia.org/wiki/Obfuscated_code

Crunch and obfuscate your code to shrink scripts here:
http://www.brainjar.com/js/crunch/demo.html

*****/

var c="          Copyright 2006 Wiimes.com - Main JavaScript file - Wiimes Release 1 Beta          ";

var c = getHTTPObject();
var url = '';
var skey = '';
var wiikey = '';
var wiiid = '';
var wid = '';
var wip = '';
var wsound = '1'; // Sound enabled by default

var poller = false;
var actimer = false; //Activity timer - disconnect from server when no activity in 3 hours
var deftitle = 'Wiimes.com - Talk with the world!';
var activeonline = 0;
var online = 0;
var loggedin = false;
var status = '0';

var timeoutId;
var tryagainId;

var win			= new Array;
var wi			= -1;	//Window Index

var active		= -1;
var zindex		= 0;

var toppos		= 50;	//Start positon of windows
var leftpos		= 50;
var	posi		= 30;

var flashTitleId;
var activeTitle;

var snd_path = "http://widget.wiimes.com/sound/";

/***** Common function - save bandwidth for getElementId *****/
function $(id){
  return document.getElementById(id);
}

/***** Reset password function *****/
function wiiResetPass(){
  alert('Lost your password?\n\nPlease contact us by using the "Contact" page.');
  return false;

  document.getElementById('password').style.display = 'none';
  document.getElementById('passwordtext').style.display = 'none';
  if (document.getElementById('email').value == ''){
    alert('Please enter a email adress,\n we will send the password to your email address.');
    document.getElementById('email').focus();
    return false;
  }

  document.getElementById('password').style.display = 'block';
  document.getElementById('passwordtext').style.display = 'block';
  return false;
}

/***** MailListAdd *****/
function MailListAdd(){
	var mail = document.getElementById("mail").value;

	if ( (mail == '') || (mail.indexOf('@') == -1) ) {
		alert('Please enter a valid email address!');
		return false;
	}

	if (maillist.readyState == 4 || maillist.readyState == 0){
		/* Make the HTTP GET request */
		maillist.open("GET",'maillist.php?mail=' + mail + '&rnd='+Math.floor(Math.random() * 1000000), true);	// Random number - no IE cache
		maillist.onreadystatechange = handlehHttpMailList;
		maillist.send(null);
	}
}

/***** handlehHttpMailList *****/
function handlehHttpMailList(){
	if (maillist.readyState == 4) {
		if (maillist.status == 200) {
			if (maillist.responseText == '1')
				document.getElementById("mailsignup").innerHTML = "You're now signed up. Thanks!";
			else if (maillist.responseText == '2')
				document.getElementById("mailsignup").innerHTML = "You're already signed up.";
			else
				document.getElementById("mailsignup").innerHTML = "Error occured: Please contact us directly instead.";
		}
	}
}

/***** Common - output to debug console window *****/
	function d(msg){

		//try{
		var dw = document.getElementById('debugwindow');
		if ((dw==null) || (dw==undefined) || (dw==false)) return;

			if (dw.value.length > 2000)
				dw.value = '';
			var today = new Date();
			//today.getTime();toGMTString()
			var hour = today.getHours();
			if (hour < 10) {hour = '0' + hour;}
			var min = today.getMinutes();
			if (min < 10) {min = '0' + min;}
			var sec = today.getSeconds();
			if (sec < 10) {sec = '0' + sec;}
			dw.value += "["+hour+":"+min+":"+sec+"]: "+msg+"\n";
			dw.scrollTop=32000;
			//setTimeout("document.getElementById('debugwindow').scrollTop=32000;",100);

		//}catch(e){}
	}

/***** Fatal error: show in red *****/
function df(msg){
  msg = '\n\n\n<fatal>'+msg+'</fatal>\n\n\n';
  d(msg);
}

/***** Change the demo widget title when user enter new title *****/
function wiiNewTitle(widgettitle){
  $('widgettitle').innerHTML = widgettitle;
}

/***** Change the demo widget size NOT IMPLEMENTED *****/
function wiiNewSize(size){
}

/***** Make the XMLHttpRequest object *****/
function getHTTPObject(){
  if (window.XMLHttpRequest) return new XMLHttpRequest();   // FireFox, Safari and IE7
  else if (window.ActiveXObject){
    var msxmls = new Array(5);
    msxmls[0] = "Msxml2.XMLHTTP.6.0";
    msxmls[0] = "Msxml2.XMLHTTP.5.0";
    msxmls[1] = "Msxml2.XMLHTTP.4.0";
    msxmls[2] = "Msxml2.XMLHTTP.3.0";
    msxmls[3] = "Msxml2.XMLHTTP";
    msxmls[4] = "Microsoft.XMLHTTP";
    for (var i = 0; i < msxmls.length; i++){
      try {return new ActiveXObject(msxmls[i]);}
      catch (e) {}
    }
  }
  throw new Error("Your browser does not support XMLHttpRequest OR ActiveX XML Request object is disabled, please upgrade to newest IE or FireFox.");
}

/***** Add a new visitor to Visitors online list *****/
function wiiAddUser() {
	var wtitle	= document.getElementById("wtitleinput").value;
	var mail	= document.getElementById("mailinput").value;
	var user 	= document.getElementById("userinput").value;
	var pass	= document.getElementById("passinput").value;

	var wsize = "0"; //if (document.getElementById('r2').checked) wsize = "1";

	var err = false;
	if ( (wtitle == '') || (wtitle.indexOf('<') != -1) || (wtitle.length<4) ) {
		document.getElementById("wtitleinput").style.backgroundColor='#FF8888';
		if (!err) { alert('Please enter a valid widget title!'); err = true;}
	}

	if ( (mail == '') || (mail.indexOf('@') == -1) || (mail.indexOf('.') == -1) || (mail.length<4) ) {
		document.getElementById("mailinput").style.backgroundColor='#FF8888';	//focus();
		if (!err) { alert('Please enter a valid email address!'); err = true;}
	}

	/* Check for blank space and NO numeric in first char */
	if ( (user == '') || (user.indexOf('@') != -1) || (user.length<4) ) {
		document.getElementById("userinput").style.backgroundColor='#FF8888';
		if (!err) { alert('Please enter a valid Wiimes ID for your account!\n Must only contain (a-z, A-Z, 0-9, _),\n and start with a letter.'); err = true;}
	}

	if ( (pass == '') || (pass.indexOf('<') != -1) || (pass.length<6) ) {
		document.getElementById("passinput").style.backgroundColor='#FF8888';
		if (!err) { alert('Please enter a valid password! (Length 6-20, a-z, A-Z, 0-9)'); err = true;}
	}

	if (err) return false;
  wiiid = user;
  
  /* Send command Add new user */
	doRequest('a','&user=' + user + '&pass=' + pass + '&mail=' + mail + '&wtitle=' + wtitle + '&wsize=' + wsize);
}

/***** *****/
function getURL(par){
	var gurl=document.location.href;
	var fi=gurl.lastIndexOf("/");
	while((fi!=-1)&&(fi>8)){
		gurl=gurl.slice(0,fi);
		fi=gurl.lastIndexOf("/");
	}
	gurl+='/'+par+'?';
	return gurl;
}

/***** Poll for new server msgs, MAIN POLL TIMER - Comet BIND is better *****/
function wiiPoll(){
  d('wiiPoll()');

  doRequest('p','&p='+status); //Poll without full refresh
}

/*****  *****/
function doRequest(cmd,param){
	//var rnd=new Date().getTime();
	url=getURL('apiw');
	if (c.readyState == 4 || c.readyState == 0){
		/* Make the HTTP GET request */
		var data = url+'c='+cmd+param;  //'&skey='+skey+
		if (wiikey!='') data+='&k='+wiikey;
		d(data+'&r='+new Date().getTime());
		c.open('POST',data+'&r='+new Date().getTime(),true);
		//document.write(data+'&r='+new Date().getTime());
		c.onreadystatechange = handleRequest;
		try{	//Needed because of Bug in FF 1.0.7
			c.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			c.send(null);
		}catch(e){
			df("Send error: Trying again");
			tryagainId = window.setTimeout("doRequest(\""+cmd+"\",\""+param+"\")",100); // 100 msec
		}
		timeoutId = window.setTimeout(function() {if (checkRequest(c) ) {c.abort();}},10000); // 10 sec
	} else {
		tryagainId = window.setTimeout("doRequest(\""+cmd+"\",\""+param+"\")",500); // 0.5 sec
		//c.abort();	//Bug in FF
	}
}

/*****  *****/
function checkRequest(xmlhttp) {
	switch(xmlhttp.readyState){
		case 1, 2, 3:
			return true;
			break;
		default:// Case 4 and 0
			return false;
			break;
	}
}

/***** New user haved signed up ok, now show information *****/
function wiiSignedUp(wiikey,wiiid){
          var su=document.getElementById('signup');
          if (su){

            embed = wiiCreateEmbed(wiikey);
            su.innerHTML='<div id="thanksbg"><span id="thanks">Thanks for signing up!</span><br/><br/><br/>'+
            '<span id="widd">Your Wiimes ID is: &nbsp;&nbsp;&nbsp;&nbsp;'+wiiid+'</span><br/>'+
            '<span id="wkey">Your Wiimes Key is: &nbsp;&nbsp;&nbsp;&nbsp;'+wiikey+'</span><br/>'+
      
            
            '<br/><center><span id="winfo">You can now sign in at the top right box!<br/>Sign in info have also been sent to your mail address.</span>'+
            
            '<br/><br/><br/><br/>'+
            '<span id="wadd">To add the Wiimes widget to any webpage, '+
            'just copy the below code,<br/>and insert it on the webpage you want the widget on :)<br/><br/></span>'+

            '</center><br/><br/><br/><br/><form name="embedform" id="embedform"><span id="embeds">Embed code: <input id="embed_code" name="embed_code" type="text" '+
            'value=\''+embed+'\' class="embed_code" onClick="javascript:document.embedform.embed_code.focus();document.embedform.embed_code.select();" readonly="true"/>'+
            
            '</span></form><br/><br/><br/>'+
            '<span id="bus"><a href="./buynow">Business?, upgrade to Wiimes Pro right now.</a></span>'+
            '</div>';
          }
          var suh=document.getElementById('youget2');
          suh.innerHTML='';
}

/***** Returns a string of embed code to insert on websites *****/
function wiiCreateEmbed(key){
  return '<!-- Begin Wiimes code. Want to talk with visitors on your website?, Go to http://www.wiimes.com! --><embed src="http://widget.wiimes.com/wiimes.swf'+
  '?'+key+'" type="application/x-shockwave-flash" wmode="transparent" width="190" height="275"></embed>';
};

/***** Handle a Request *****/
function handleRequest(){
	if ((c != undefined) && (c.readyState == 4)){
		//window.clearTimeout(timeoutId);
		var statusc = "";var statust = "";
		try{	//Needed because of Bug in FF 1.0.7
			statusc = c.status;
			statust = c.statusText;
		}catch(e){
			df("Network error: "+statust);
			return false;
		}
		if (statusc == 200){	//Only set when State=4, need to be 200=OK
			try{
				var cxml = c.responseXML.documentElement.tagName;
			}catch(e){
				df('responseXML: Not valid xml data!['+c.responseText+']');
				return false;
			}
			if (cxml == ''){
				df('responseXML: Not valid xml data!['+c.responseText+']');
				return false;
			}
			var xd = c.responseXML;
			d('G: '+c.responseText); //alert(c.responseText);

			/* Check for parse error */
			if (isIE){
				if (xd.parseError.errorCode != 0){
					d('IE parseError: '+xd.parseError.reason+' T: '+c.responseText);
					return false;
				}
			}else{
				if (xd.documentElement.tagName == 'parsererror'){
					d('FF parseError: 0');
					return false;
				}
			}
			
			//d('CMD: '+xd.documentElement.tagName);

			//d('TAG: '+xd.getElementsByTagName('ler')[0].nodeName );
			try{
        d('CMD: '+xd.documentElement.tagName );
			}catch(e){
				d('No cmd given');
				return false;
			}

			cmd = xd.documentElement;
			switch(cmd.nodeName){

        case"oka":	/* Signup ok */

          var su=$('signup');
          if (su){
            wiikey = cmd.getAttribute('k');
            wiiSignedUp(wiikey,wiiid);
          }
					break;
					
				case"era":  /* Signup already taken error */
          $("userinput").style.backgroundColor='#FF8888';
          alert("Sorry, Wiimes ID already exist! Please choose another.");
					break;
					
				case"erl":	/* Login error */
					d('G: Login error!');

          clearTimeout(nnet); //Clear No response timer
          $('errortext').style.color = 'red';
          $('errortext').innerHTML = 'Your signin where incorrect!<br/>';
					break;

				case"okl":	/* Login ok */
          d( 'G: Login accepted!' );

          clearTimeout(nnet); //Clear No response timer
          $('errortext').innerHTML = 'Success!';

          loggedin = true;

					wiikey = cmd.getAttribute('k');
					d( wiikey );

          wiiStart(); //Logged in - so start wiimes now!

          /* Go ONLINE */
          wiiGoOnLine()

          /* START HTTP POLLING CONNECTION */
					poller = setInterval("wiiPoll()",3500);
					doRequest('p','&p1=r');  //Poll with full reload - only sent first time

					wiiResetTimer(); //Start inactivity timer

          addEvent(document,'mousemove',wiiResetTimer,true);
          addEvent(document,'keypress',wiiResetTimer,true);

					break;


        case"f":	/* Feeback sent ok */
          $('feedbackStatus').innerHTML = 'Thanks!';
					break;

        case"vok":	/* Change status ok */
					break;

        case"ver":	/* Change status error */
					break;

				case"p":
					var node;
					for(i=0;((node=cmd.childNodes[i])!=undefined); i++){
						d('I:'+i+' '+node.nodeName);
						switch(node.nodeName){
						case"pnc":

							var uid = node.getAttribute('i');
							var uname = unescape(node.getAttribute('u'));
							d( 'G: Poll - New chat user: '+uid+' '+uname );

							wiiNewUser(uid, uname);
							break;
						case"pnm":
							var uid = node.getAttribute('i');
							var umsg = unescape(node.getAttribute('m'));
							d( 'G: Poll - New msg: '+uid+':'+umsg );

							wiiNewChatMsg(uid, decodeURIComponent(umsg),false);
							break;
						case"pnr":
						  var uid = node.getAttribute('i');
						  var uname = unescape(node.getAttribute('u'));
						  //online--;
						  wiiRemoveUser(uid, uname);
						  break;
						case"nno":
						  var uid = node.getAttribute('i');
						  var uname = unescape(node.getAttribute('u'));
						  wiiChangeNick(uid, uname);
						  break;
						default:
							break;
						}

					}

					break;

				case"ser":
					break;
				case"sok":
					break;
				case"mok":
					break;
				case"mer":
					break;
				case"www":
					break;
				default:
					d('G: Protocol error!='+cmd.nodeName);
					return;
			}


			
		}
	}
}

/***** GetScreenWidth *****/
function getScreenWidth() {
        if (isIE()) { // IE is buggy in multi-monitor-mode
            var screenWidth = document.documentElement.offsetWidth;
            var screenHeight = document.documentElement.offsetHeight;
        } else {
            var screenWidth = screen.width;
            var screenHeight = screen.height;
        }
        var width1 = width2 = 1024;
    
        if (screenWidth >= 1260) width1 = 1280;
    if (screenWidth < 1260 && screenWidth > 820) width1 = 1024;
    if (screenWidth < 1004) width1 = 800;
    if (screenHeight > 768) width2 = 1280;
    if (screenHeight <= 768 && screenHeight > 600) width2 = 1024;
    if (screenHeight <= 600 && screenHeight > 576) width2 = 800;
        return Math.min(width1, width2);
}


/************************* Adress bar commands ********************************/
function debug(){
	wiiCreateDebugWindow();
}

function exit(){
	clearInterval(poller);
}
/************************* END Adress bar commands ********************************/



/***** Reset Inactivity timer *****/
function wiiResetTimer(){
  clearInterval(actimer);
  actimer = setInterval("wiiInActive()",1000*60*60*18);  //Inactivity=12+6 hours
}

/***** No user activity in 3 hours - then SignOut *****/
function wiiInActive(){
  clearInterval(actimer); // No 2 times..
  clearInterval(poller);  // Stop poll timer
  doRequest('e','');      //Set user offline status on server
  wiiSignOut();
  alert("You have been logged out, due to inactivity!");
}


/***** Create debug window - ONLY for debugging *****/
function wiiCreateDebugWindow(){
	wi++;	//Increment window count
	win[wi] = new uiClass();
	win[wi].createNewWindow('Wiimes Debug Window','wiimesdebug','500','600','700','40');

	win[wi].setActive();

	//win[wi].shakeWindow();

	win[wi].setContext("<textarea width=95% height=500px style=\"overflow:auto;margin:10px;width:95%;height:550px;\" nowrap=\"false\" name=\"debugwindow\" id=\"debugwindow\">"+
	"\nEvent: Debug window created!\n"+
	"</textarea><a href='javascript:d(document.documentElement.innerHTML);'>HTML</a>");

	//doRequest('test');
}

function wiiBlog(){
	wiiCreateBlogWindow();
}

function wiiFeedBack(){
	wiiCreateFBWindow();
}

function wiiSettings(){
	wiiCreateSWindow();
}

function wiiHelp(){
	window.open("http://wiki.wiimes.com/wiki/doku.php", "_blank");
}

function wiiCreateYouTubeWidget(){
	wi++;	//Increment window count
	win[wi] = new uiClass();
	win[wi].createNewWindow('YouTube Video Search','youtubewidget',425+9,350+45,400,170);
	win[wi].setActive();
	win[wi].setContext("<div id=\"youtubewidget\" class=\"youtubewidget\"></div>");
	var wb = $('youtubewidget');
	wb.innerHTML = '<div id="youtubewidgetcontext">'+
	'<span class="blogtitle">Video from YouTube!</span><br/>'+
	'<div id="ytv"></div><br/>'+
	'<br/>'+
  '</div>';

  $('ytv').innerHTML = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="425" height="350"><param name="movie" value="http://www.youtube.com/v/7PTvr755V8s"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/7PTvr755V8s" type="application/x-shockwave-flash" wmode="transparent" width="425" height="350"></embed></object>';
}

function wiiCreateBlogWindow(){
  
	wi++;	//Increment window count
	win[wi] = new uiClass();
	win[wi].createNewWindow('Wiimes Blog','wiimesblog',250,290,100,170);
	win[wi].setActive();
	win[wi].setContext("<div id=\"wiimesblog\" class=\"wiimesblog\"></div>");
	var wb = $('wiimesblog');

	/*wb.innerHTML = '<div id="wiimesblogcontext">'+
	'<span class="blogtitle">Wiimes Blog</span>&nbsp;'+
	'<span class="blogdate">Posted on 20-12-2006</span><br/>'+
	'<br/>Welcome to Wiimes :)<br/>'+
	''+
	'We are <b>very</b> proud to say,<br/>that we have launched into Public Beta!<br/>'+
	'<br/>'+
	'<b>What is Wiimes?</b><br/>'+
	'Wiimes is a instant messenger for the web!<br/>'+
	'This means that you can place a wiimes chat widget on ANY website, blog, or.. '+	
	'<br/>This enables you to IM directly with people visiting your website.<br/><br/>'+
	
	'<b>What can you use it for?</b>'+
	'<br/>It have a wide range of uses, a good example is a small business that want a easy way to talk with website customers.<br/>Using <a href="http://www.wiimes.com/pro" target="_blank">Wiimes Pro</a> this is possible - even all over the world!<br/>'+
	'<br/>Since it still in beta, you may encounter some small bugs,<br/>send us some feedback if you find some!<br/>'+
	'<br/>'+
	'<b>Hope you enjoy it!</b>'+
	'<br/>'+
	'<br/>'+
	'</div>';*/
	
	wb.innerHTML = '<div id="wiimesblogcontext">'+
	'<span class="blogtitle">Wiimes Blog</span>&nbsp;'+
	'<span class="blogdate">Posted on 08-01-2007</span><br/>'+
	'<br/>Welcome to Wiimes :)<br/>'+
	'<br/>'+
	'<b>Wiimes got a little upgrade:</b><br/>'+
	'1. You can now hear a sound,<br>'+
  '&nbsp;&nbsp;&nbsp;&nbsp;when someone sends a<br/>&nbsp;&nbsp;&nbsp;&nbsp;message to you.<br/>'+
	'2. Other small bugs corrected.<br/>'+
	'<br/>'+
	'<b>What is Wiimes?</b><br/>'+
	'Wiimes is a instant messenger for the web!<br/>'+
	'This means that you can place a wiimes chat widget on ANY webshop, website, blog, or.. '+	
	'<br/>This enables you to talk directly with people visiting your website!<br/><br/>'+
	
	'<b>What can you use it for?</b>'+
	'<br/>It have a wide range of uses, for example a small business could use is as a easy way to talk with customers.<br/>Using <a href="http://www.wiimes.com/pro" target="_blank">Wiimes Pro</a> this is possible - all over the world!<br/>'+
	'<br/>Since it still in public beta, you may encounter some small bugs,<br/>send us some feedback if you find some!<br/>'+
	'<br/>'+
	'<b>Hope you enjoy it! ;)</b>'+
	'<br/>'+
	'<br/>'+
	'</div>';


	 $('wiimesblogcontext').style.overflow='auto';
}

function wiiCreateHelpWindow(){
	wi++;	//Increment window count
	win[wi] = new uiClass();
	win[wi].createNewWindow('Wiimes Help','wiimeshelp',250,270,100,170);
	win[wi].setActive();
	win[wi].setContext("<div id=\"wiimeshelp\" class=\"wiimeshelp\"></div>");
	var wb = $('wiimeshelp');
	wb.innerHTML = '<div id="wiimeshelpcontext">'+
	'<span class="blogtitle">Need help?!</span><br/>'+
	'<span class="blogdate"></span><br/>'+	//14:00 GMT
	'Hi, and welcome to Wiimes :)<br/>'+
	'<br/>'+
	'We will soon be launching!<br/>'+
	'Watch this space..<br/>'+
	'<br/>'+
	'<b>So - what is Wiimes?</b><br/>'+
	'Wiimes is a messenger for the web!<br/>'+
	'Just place a wiimes chat widget on your site, '+
	'and start talking with people watching your site or blog.<br/>'+
	'Easy and smart!<br/>'+
	'<br/>'+
	'Hope you enjoy!'+
	'</div>';
}

function wiiSendFeedBack(){
  fbMail = $('feedbackMail');
  fbMsg = $('feedbackMsg');
  fbSta = $('feedbackStatus');

  if (fbMsg.value==''){
    fbSta.innerHTML = 'No feedback to send!';
    return false;
  }

  //Email is optionel for now..

  fbSta.innerHTML = 'Sending..';
  fbts = new Date().getTime();//.toGMTString();
  doRequest('f','&p='+encodeURIComponent(ehtml(fbMail.value))+'&p1='+encodeURIComponent(ehtml(fbMsg.value))+'&p2='+unescape(fbts));

  fbMail.value = '';
  fbMsg.value = '';
}

function wiiCreateFBWindow(){
	wi++;	//Increment window count
	win[wi] = new uiClass();
	win[wi].createNewWindow('Send us your feedback','wiimesfb',290,300,150,180);
	win[wi].setActive();
	win[wi].setContext("<div id=\"wiimesfb\" class=\"wiimesfb\"></div>");
	var wfb = $('wiimesfb');
	wfb.innerHTML = '<div id="wiimesfbcontext" style="display: block">'+
	//'<span class="fbtitle">Feedback to us!</span><br/>'+
	'Found a bug, a new feature, or something else?</br>'+
	
	'<table cellpadding="0" cellspacing="0" class="form1Table" style="margin-top:5px;text-align:left;">'+
	'<tr><td valign="top"><span class="fbLabel">Your email:</span></td></tr>'+
	'<tr><td><input id="feedbackMail" value="Your mail here" name="mail" class="inputfb" size="41" type="text" onfocus="this.select();"/></td></tr>'+
	'<tr><td valign="top"><span class="fbLabel">Your message:</span></td></tr>'+
	'<tr><td><textarea id="feedbackMsg" name="feedback" class="inputfb" cols="42" rows="10" style="" onfocus="this.select();">Your feedback here</textarea></td></tr>'+
	'</table>'+
	'<span id="feedbackStatus"></span><input id="feedbackSend" type="submit" value="Send feedback" onclick="wiiSendFeedBack();" class="buttonfb" style="position:absolute;width:110px;height:25px;left:160px;"/>'+
	''+
	''+
	''+
	''+
	''+
	''+
	'</div>';
	if (isFF) $('feedbackMsg').style.fontSize = '12px';
}

// Create settings window
function wiiCreateSWindow(){
	wi++;	//Increment window count
	win[wi] = new uiClass();
	win[wi].createNewWindow('Settings','wiimesse',300,230,290,200);
	win[wi].setActive();
	win[wi].setContext("<div id=\"wiimesse\" class=\"wiimesse\">Settings dialog is not fully working yet,<br/>it will soon be working :)<br/></div>");
}

/***** Activated when window is resized *****/
//document.body.onresize = wiiResize;
//addEvent(document,'resize',wiiResize,true);
wiiResize = function(){
  var wlw = $('wwiimeslist');
  if (wlw==null) return;

  if (isIE) { // IE is buggy in multi-monitor-mode
            var screenWidth = document.documentElement.offsetWidth;
            var screenHeight = document.documentElement.offsetHeight;
        } else {
            var screenWidth = screen.width;
            var screenHeight = screen.height;
    }
	
	var he =  screenHeight-5-10;
	var che = (screenHeight-5-10-58);
	if (isIE == false){	//Firefox 1.x FIX
		he -=  200;//screenHeight-5-10-200;	
		che -= 200;//(screenHeight-5-10-58-200);
	}

  wlw.style.top = 5+'px';
  wlw.style.left = screenWidth-210+'px';
  wlw.style.height = he+'px';
  
  $('wwiimeslist').getElementsByTagName('table')[0].rows[2].style.height = he-37+'px';
  var tm=$('wiimeslist');
  if (tm!=null)
    tm.style.height = che+'px';
}

/***** Go online *****/
function wiiGoOnLine(){
  if (status!='1'){
    d('GoOnline');
    doRequest('v','&p=1'); //Set user status 1=ONLINE
    status='1';            //Set user status local 1=ONLINE
  }
}

/***** Go offline *****/
function wiiGoOffLine(){
  if (status!='0'){
    d('GoOffline');
    doRequest('v','&p=0'); //Set user status 0=OFFLINE
    status='0';            //Set user status local 1=OFFLINE
  }
}

function wiiCreateUsersWindow(){
    if (isIE) { // IE is buggy in multi-monitor-mode
            var screenWidth = document.documentElement.offsetWidth;
            var screenHeight = document.documentElement.offsetHeight;
        } else {
            var screenWidth = screen.width;
            var screenHeight = screen.height;
    }

	wi++;	//Increment window count
	win[wi] = new uiClass();
	
	var he =  screenHeight-5-10;
	var che = (screenHeight-5-10-58);
	if (isIE == false){	//Firefox 1.x FIX
		he -=  200;//screenHeight-5-10-200;	
		che -= 200;//(screenHeight-5-10-58-200);
	}
	win[wi].createNewWindow('Visitors list','wiimeslist','200',he,screenWidth-210,'5');

	win[wi].setActive();

	//win[wi].shakeWindow();

	win[wi].setContext("<div id=\"listtop\"><div id=\"liston\" onclick=\"wiiGoOnLine();\"><input type=\"radio\" name=\"status\" value=\"Online\" checked=\"checked\" onfocus=\"wiiGoOnLine();\"/>Online</div><div id=\"listoff\" onclick=\"wiiGoOffLine();\"><input type=\"radio\" name=\"status\" value=\"Offline\" onfocus=\"wiiGoOffLine();\"/>Offline</div></div>"+
  "<div id=\"wiimeslist\" class=\"wiimeslist\">"+
  "<p id='noneonline'>No visitors</p>"+
  "</div><div id=\"wiimesonline\">0</div>");
	$('wiimeslist').style.height = che+'px';
}

/***** Change the < > *****/
function ehtml(str)
{
	var tmp = String(str);
	tmp = sar(tmp, "<", "&lt;");
	tmp = sar(tmp, ">", "&gt;");
	tmp = sar(tmp, "&", "&amp;");
	tmp = sar(tmp, "\"", "&quot;");
	tmp = sar(tmp, "\'", "&apos;");
	return (tmp);
}

/***** Search And Replace *****/
function sar(str, search, replace)
{
	var t2 = str.split(search);
	var t1 = t2.join(replace);
	return (t1);
}

/***** Make all www https links clickable *****/
function wiiMakeLinks(str){
	var regex=/(^|[^'\"])(\bhttps?:\/\/[^\s\"\<\>]+)\b/ig;
	var rep="$1<a href=\"$2\" target=\"_blank\">$2</a>";
	str=str.replace(regex,rep);

	var regex=/(^|[^'\"])(^|\s+)(www\.[^\s\"\<\>]+)\b/ig;
	var rep="$1$2<a href=\"http://$3\" target=\"_blank\">$3</a>";
	str=str.replace(regex,rep);

	return str;
}

/***** Send a IM back to server *****/
function wiiSendIM(uid,im){
  wiiResetTimer();
	var m = im.value;
	if (m.length < 3){
		im.value="";
		im.focus();
		return false;	//If no text - and only line break = length=2
	}
	m = m.substr(0, (m.length >= 128) ? 128 : m.length );
	m = sar(m,"\0x10","");
	m = sar(m,"\n","");
	doRequest('m','&p='+uid+'&p1=s'+'&p2='+encodeURIComponent(ehtml(m)));
	wiiNewChatMsg(uid,m,true);
	im.value="";
	im.focus();
}

function updateOnline(){
  var wo = $('wiimesonline');
  wo.innerHTML = online;
}

function wiiNewUser(uid, uname){
	online++;
	updateOnline();
	var wl = $('wiimeslist');
	if ($('noneonline') != null){
    wl.innerHTML = '';
  }
	wl.innerHTML += "<div class=\"wiimesListItem\" id=\"wl"+uid+"\" onmouseover=\"this.style.backgroundColor='#eee';\" onmouseout=\"this.style.backgroundColor='#fff';\" onclick=\"wiiNewChatWindow('"+uid+"', '"+uname+"');\">"+uname+"</div>";
	
	/* If window open - update status */
	wiiUserGoesOnline(uid, uname);
}

function wiiRemoveUser(uid, uname){
	online--;
	updateOnline();
  
	wiiNewChatMsg(uid,'Visitor have gone offline.',3);
	
	wuid = $('wl'+uid);
	if (wuid != null) wuid.parentNode.removeChild(wuid);
	
	suid = $('status_'+uid);
  if (suid != null) suid.innerHTML=uname+" is offline";
}

function wiiUserGoesOnline(uid, uname){
  wiiNewChatMsg(uid,'Visitor is back online.',3);

	suid = $('status_'+uid);
  if (suid != null) suid.innerHTML=uname+" is online";
}

/*****  *****/
function wiiChangeNick(uid, uname){
  d(uid+' '+uname);
  wiiNewChatMsg(uid,'Visitor have changed nickname to '+uname+'.',3);
  wuid = $('wl'+uid);
  if (wuid != null){
    wuid.innerHTML = uname;
    wuid.onclick="wiiNewChatWindow('"+uid+"', '"+uname+"');"; //FIXME test in all browsers
  }

  cuid = $('c'+'w'+'t'+uid);
  if (cuid != null) cuid.innerHTML='Chat with '+uname;

	suid = $('status_'+uid);
  if (suid != null) suid.innerHTML=uname+" is online";  //Must be online..
}

/*****  *****/
function wiiNewChatWindow(uid,username){
	wi++;	//Increment window count
	win[wi] = new uiClass();
	win[wi].nickname = username;
	var s = win[wi].createNewWindow('Chat with '+username,'t'+uid,'300','250');
	if (s){
		win[wi].setContext("<div class=\"talkfield\" id=\"m"+uid+"\"></div>"+
		"<textarea onkeydown=\"wiiStopFlash()\" onkeyup=\"if(event.keyCode==13){ wiiSendIM(\'"+uid+"\',this);}\" class=\"sendfield\" id=\"s"+uid+"\"></textarea>"+
		"<div class=\"statusfield\" id=\"status_"+uid+"\"></div>"
		);
		document.getElementById('status_'+uid).innerHTML=username+" is online";
		win[wi].setActive();
	}else
		d('Fail: Window id already exist!');
}

function wiiNewChatMsg(uid,umsg,ttype){
	var testw = document.getElementById('m'+uid);
	var chke = document.getElementById('wl'+uid);
	if (chke != null){
		username = chke.innerHTML;
	}else{
		return false;	//No such uid on our "Users list"
	}
	if (testw){
		//win[wi].setActive();
	}else{
    if (ttype==3){
      return false;//No new wiimes window on offline mode..
    }else{
      wiiNewChatWindow(uid, username);
      testw = document.getElementById('m'+uid);
    }
	}
	
	//if (!testw || !username){return false;}

		//test.innerHTML += '<b>'+umsg+'</b><br/>\n';
			//if (testw.innerHTML.length > 100000)	testw.innerHTML = '';	//In chase of REALLY long chat!
		var today = new Date();
		var hour = today.getHours();
		if (hour < 10) {hour = '0' + hour;}
		var min = today.getMinutes();
		if (min < 10) {min = '0' + min;}
		//d(testw.innerHTML);
		
		if (ttype){
			from = wid;
			color = '#D35900';//'#336699';
		}else{
			from = username;//win[1].nickname;
			color = '#0163B3';

		}

    umsg = wiiMakeLinks(umsg);  //Make links clickable

		if (ttype==3){
		color = '#CCCCCC';
		testw.innerHTML += "<span><span style=\"font-size:10px;color:"+color+"\">["+hour+":"+min+"] "+'Wiimes message'+': '+umsg+'</span><br/></span>';
		}else{
		testw.innerHTML += "<span><span style=\"font-size:12px;color:"+color+"\">["+hour+":"+min+"] "+from+': </span>'+umsg+'<br/></span>';
		}
    //d(testw.innerHTML);
		//testw.style.height = '100px';
		testw.scrollTop=32000;

    // Flash title if we received a new msg
    if (ttype==false) wiiTitleFlash(username);

    if (ttype==0){
      // Play Received Sound
      wiiPlaySound("receives");
    }else if (ttype==1){
      // Play Send Sound
      //wiiPlaySound("sends");
    }else{
      // Play User1 Sound
      //wiiPlaySound("user1s");
    }

		return true;
	
}

function wiiTalk(talkid){
	wi++;	//Increment window count
	win[wi] = new uiClass();
	win[wi].createNewWindow('Talk with '+talkid,talkid,'300','350');
	win[wi].setActive();
	win[wi].shakeWindow();
	win[wi].setContext("<div id='"+talkid+"'></div>");
}




function wiiSignOut(){
	//Make a logoff request - end session
	doRequest('e','');

	document.location = 'http://www.wiimes.com/';
}

function wiiSignIn() {
		var allok = 1;

		document.getElementById('errortext').style.color = 'red';
		document.getElementById('errortext').innerHTML = '';
		signInBtn = document.getElementById('signinbutton');

		if (document.getElementById('password').value == '')
		{
			allok = 0;
			document.getElementById('errortext').innerHTML = 'You need to enter a password!<br/>';
			
			document.getElementById('password').focus();
			document.getElementById('password').style.backgroundColor='#FF8888';
		}

		if (document.getElementById('wiimesid').value == '')
		{
			allok = 0;
			document.getElementById('errortext').innerHTML = 'You need to enter a ID!<br/>';
			document.getElementById('wiimesid').focus();
			document.getElementById('wiimesid').style.backgroundColor='#FF8888';
		}
		if (allok == 0) {
			return false;
		}

	
	//d(wuser+' '+wpass);
  //alert(wid);
	wid = document.getElementById('wiimesid').value;
	wip = document.getElementById('password').value;

          var remember = document.getElementById('remember');
          if ((remember) && (remember.checked==true)){
            setCookie("wid",wid,20);
          }else{
            //Delete cookies
            deleteCookie('wid');
          }

  wiiEncryptAndSendPass(wid,wip);
}

function wiiShowSignedIn() {
  return;
}

function wiiToPass(f) {
  var wif=document.getElementById('wiimesid');
  var pwf=document.getElementById('passwordf');
  f.style.color = '#000000';

  //f.style.color = '#000000';
  
  if (f.value=='Enter Wiimes ID') f.value='';
  //var pva=f.value;
  if ((f.name=='pass')){
    pwf.innerHTML="<input style=\"color:#000;\" type=\"password\" id=\"password\" name=\"pass\" style=\"width: 160px;\" value=\"\" autocomplete=\"on\" class=\"flatinput\" size=\"24\" onblur=\"this.style.backgroundColor='#FFFFFF';wiiUiBlur(this);\" onfocus=\"this.style.backgroundColor='#FFFFFD';select();\" onkeyup=\"javascript:if(event.keyCode==13) wiiSignIn();this.style.backgroundColor='#FFFFFD';\"/>";
    document.getElementById('password').value='';
    
    setTimeout("document.getElementById('password').focus();",1);
  }
  //if (f.name=='pass') pwf.type = 'password';
}

function wiiUiBlur(f) {
  var wif=document.getElementById('wiimesid');
  var pwf=document.getElementById('passwordf');
  
  //f.value='';
  //if (f.name=='pass') pwf.type = 'password';
  if ((f.value=='')&&(f.name=='login')){
    //pwf.type = 'text';
    f.value='Enter Wiimes ID';
    f.style.color = '#aaaaaa';
  }

}

function wiiShowSignInBox(){
  var remb='checked';
	if ((wid=='')||(wid==undefined)||(wid==null)||(wid=='undefined')) remb='';

  if (wid != ''){
    var twid=document.getElementById('wiimesid');
    twid.value = wid;
    twid.style.color='#000000';
    setTimeout("wiiToPass(document.getElementById('password'));",1);
  }
  //if (wip != '') document.getElementById('password').value = wip;
	document.getElementById('remember').checked = remb;
}


function getSettings(){
	wid = getCookie('wid');  //wip = getCookie('wip');
	wsound = getCookie('wsound');
	if ((wsound=='1') || (wsound=='0')) {} else wsound='1';

	wiiShowSignInBox();

	wiiPreLoad();  //Preload images
}

function wiiSetSound(){
  if (wsound=='1') wsound='0'; else wsound='1';
  setCookie('wsound',wsound,1);  //Save sound selection in cookie
  //Change speaker icon
}

function setCookie(cookieName,cookieValue,nDays){
	var today = new Date();
	var expire = new Date();
	if (nDays==null || nDays==0) nDays=1;
	expire.setTime(today.getTime() + 3600000*24*nDays);
	document.cookie = cookieName+"="+escape(cookieValue)+";domain=.wiimes.com;expires="+expire.toGMTString();
}

function getCookie(name){
	var start = document.cookie.indexOf(name+"=");
	var len = start+name.length+1;
	if ((!start) && (name != document.cookie.substring(0,name.length))) return '';
	if (start == -1) return '';
	var end = document.cookie.indexOf(";",len);
	if (end == -1) end = document.cookie.length;
	return unescape(document.cookie.substring(len,end));
}

function deleteCookie(name){
   if (getCookie(name)) document.cookie = name + "=" + ";domain=.wiimes.com; expires=Fri, 31 Dec 1999 23:59:59 GMT;";
} 

















var isIE = false;
var isVer = 0;
var isOS;

var	isIE = wiiIsBrowser("MSIE");
var isIE7=( isIE && isVer>=7 );
var	isFF = wiiIsBrowser("Firefox");
var isNS=wiiIsBrowser("Netscape6/");
var isSafari=wiiIsBrowser("Safari");
var isGecko=wiiIsBrowser("Gecko");

var isWin=wiiIsOS("win");
var isMac=wiiIsOS("mac");
var isLinux=wiiIsOS("linux");
var isUnix=wiiIsOS("x11");

var isHttps=(document.location.href.indexOf("https")==0);

/******************************************************************************/
function wiiIsBrowser(name){
	var ua=navigator.userAgent;
	d("wiiIsBrowser: "+ua);
	if ((i=ua.indexOf(name))>=0) {
		browserVer=parseFloat( ua.substr(i+name.length) );
		d("wiiIsBrowserVersion: "+browserVer);
		return true;
	}
	return false;
}

function wiiIsOS(name){
	var ua=navigator.userAgent.toLowerCase();
	return (ua.indexOf(name)>=0);
};




function wiiInit(){
	isIE = wiiIsBrowser("MSIE");
	//isIE7=(isIE&&version>=7);
	isFF = wiiIsBrowser("Firefox");
	isNS = wiiIsBrowser("Netscape6/");
	isSafari = wiiIsBrowser("Safari");
	isGecko = wiiIsBrowser("Gecko");
}

function wiiStart(){
	wiiInit();
	wiiShowStart();

	wiiCreateUsersWindow();
	wiiCreateBlogWindow();
	//wiiCreateYouTubeWidget();
	//wiiCreateDebugWindow();
}



function wiiShowStart() {
	document.body.innerHTML =
	'<div id="wiiapp">'+
	
	'<img id="wlogo" src="./i/skin/bb1.gif" alt="Wiimes.com" title="Wiimes.com" />'+
	''+
	'<div id="wlinks">'+
	'<span class="wlinksa"><a href="javascript:wiiSignOut();">Sign Out</a></span>|'+
	'<span class="wlinksa"><a href="javascript:wiiHelp();">Help</a></span>|'+
	'<span class="wlinksa"><a href="javascript:wiiFeedBack();">Feedback</a></span>|'+
	'<span class="wlinksa"><a href="javascript:wiiSettings();">Settings</a></span>|'+
	'<span class="wlinksa"><a href="javascript:wiiBlog();">Blog</a></span>'+
	'</div>'+

	'<div id="wwelcome">'+
	'<span class="wlinksa">Welcome \''+wid+'\'!</span>'+
	'</div>'+

	'<div id="preload" style="visibility: hidden">'+
	
	'</div>';
	document.body.style.backgroundImage = "url(./i/skin/bgskin.gif)";
	document.body.style.backgroundColor = '#A5B8CD';

  /* Load sound.swf - for sound playback */
  wiiLoadFlashSound();

	/* Arrange visitor list on resize FIXME make a timer os FireFox 1.x also works */
	window.onresize = wiiResize;
	//window.onbeforeunload = wiiUnload;
	//window.onunload = wiiSignOut;
}

wiiUnload = function(){
  return "If you do, you will end all active conversations!";
}

/* Loads the Flash sound module */
function wiiLoadFlashSound(){
  //d('LoadEmbedSound');
  var isFlash = true;
  var sndid = 'sound';

  if (isFlash){
    var sndo=document.createElement("div");
    //var tmp1="<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" id=\""+sndid+"\" name=\""+sndid+"\" width=\"1\" height=\"1\" align=\"middle\">";
    //tmp1+="<param name=\"wmode\" value=\"transparent\" />";
    //tmp1+="<param name=\"bgcolor\" value=\"#FFFFFF\" />";
    //tmp1+="<param name=\"quality\" value=\"high\" />";
    //tmp1+="<param name=\"allowScriptAccess\" value=\"sameDomain\" />";
    //tmp1+="<param name=\"movie\" value=\""+snd_path+"sound.swf\" />";
    var tmp1="<embed src=\""+snd_path+"sound.swf\" quality=\"high\" bgcolor=\"#FFFFFF\" width=\"1\" height=\"1\" id=\""+sndid+"\" name=\""+sndid+"\" align=\"middle\" allowScriptAccess=\"sameDomain\" swLiveConnect=\"true\" type=\"application/x-shockwave-flash\" />";
    //tmp1+="</object>";
    sndo.innerHTML=tmp1;
    document.body.appendChild(sndo);
  }
}
/* PlaySound - Test=javas + cript:wiiPlaySound("sends"); */
function wiiPlaySound(sndid){
  var sndo = $('sound');
  
  //if (isFF){
  //  var movie = window.document.sound;
  //  sndo = movie[1];
  //  d('ff: '+sndo);
  //}else{
    
  //}
  
  if ((sndo!=null) && (wsound=='1')){
    try{
      sndo.TCallLabel("/"+sndid,"play");  //Call our sound.swf object
    }catch(e){
      //alert('Error: Please instll Flash!');
      d('FATAL: Error play sound!');
    }
  }
}


/* Run on body onload event */
function wiiPreLoad(){
	wiiPreloadImages();
}

/***** Preload window images into preload div element *****/
function wiiPreloadImages(){
	var ple = document.getElementById("preload");if (!ple) return;
	var imgt = "";
	var imgs=["nw.gif","n.png","ne.gif","barw.png","barn.png","bare.png","w.png","e.png","sw.gif","s.png","se.png","close.gif","close_over.gif","close_down.gif","buttons/close.gif","buttons/close_hot.gif","buttons/close_down.gif","skin/sl.gif","skin/sl2.gif","skin/bb.gif"];
	for(var i=0;i<imgs.length;i++){
		imgt+="<img src='"+"./i/wbox/"+imgs[i]+"'>";
	}
	ple.innerHTML = imgt;
}

function removeElement(divNum) {
  var d = document.getElementById('wiiapp');
  var olddiv = document.getElementById(divNum);
  d.removeChild(olddiv);
}

function rem() {
	var t = document.getElementById('test');
	t.parentNode.removeChild(t);
}

function addEvent(obj,evType,fn,useCapture){
	var ret=false;
	if(obj!=null){
		if(obj.addEventListener){
			obj.addEventListener(evType,fn,useCapture);
			ret=true;
		}
		else if(obj.attachEvent){
			obj.attachEvent('on'+evType,fn);ret=true;
		}
		}
	return ret;
}





function wiiTitleFlash(m){
	d('wiiTitleFlash');
	
	activeTitle = m;
	clearInterval(flashTitleId);
	flashTitleId=setInterval('wiiflash()',1000);

}

function wiiStopFlash(){
	clearInterval(flashTitleId);
	document.title=deftitle;
}

function wiiflash(){
	if (document.title==deftitle){
		document.title=activeTitle;
	}else{
		document.title=deftitle;
	}
}








/*****  *****/
if (document.getElementById('wiimesid')) { document.getElementById('wiimesid').focus(); }






















/* START CLASS UI */
function uiClass() {

this.w_id			= null;		// The ID off the class
this.winId			= null;
this.w_divElement	= null;		// Class name
this.w_windowFrame	= null;
this.w_name         = '';

this.nickname = '';

var shakecount = 0;
var x=0;
var y=0;

var xOffset = null;
var yOffset = null;

this.w_width = null;
this.w_height = null;

var this_element = null;

this.init = function(e){
	this_element = this;
	this.w_id = e;
	this.w_divElement = e;
	this.w_divElement.style.zIndex = zindex;
	
	this.winId = wi;
	
};


this.createNewWindow = function(titleis,nameis,widthis,heightis,xpos,ypos){
	var wiiapp = document.getElementById('wiiapp');
	if (!wiiapp) return false;	//Error - No place to put window on
	
	var tocreate = document.getElementById('w'+nameis);
	if (tocreate){
		this.w_divElement = tocreate;
		this.setActive();	//Set window active instead
		return false;	//Error - Window id already exist
	}

	var d = document.createElement('div');
	d.id = 'w'+nameis;	// Window ID

	wiiapp.appendChild(d);

	if (xpos){
		d.style.position = 'absolute';
		d.style.top = ypos+'px';
		d.style.left = xpos+'px';
	}else{
		this.setStartPosition(d);	//Sets the window intial position
	}

	d.style.width = widthis+'px';
	d.style.height = heightis+'px';

	this.init( d );
	
	this.w_width  = widthis;
	this.w_height = heightis;
	
	this.createWindow();
	this.setCaption(titleis);
	
	return true;
}

this.setStartPosition  = function(d){
	if (toppos > 400) toppos = 40;
	if (leftpos > 800) leftpos = 40;
	toppos += posi;
	leftpos += posi;
	d.style.position = 'absolute';
	d.style.top = toppos+'px';
	d.style.left = leftpos+'px';
}

this.createWindow = function(windowname){
	var bgh = this.w_height - 37;

	var _714 = ' style=\"cursor: pointer;\" ';
	var _715="8px";

	var html = '<table style="" id="window" border=0 cellpadding=0 cellspacing=0 width=100% height=100%>';
html+="<tr width=100% height=\"8px\">";
html+=" <td id=\"nw\" class=\"uiDlgNW\""+_714+"><img id=\"nwwimg\" src=\"./i/wbox/nw.gif\" style=\"display: block;\"></td>";
html+=" <td id=\"n\" class=\"uiDlgN\""+_714+"><img id=\"nwimg\" src=\"./i/wbox/n.png\" width=\"100%\" height=\"8px\" style=\"display: block;\"></td>";
html+=" <td id=\"ne\" class=\"uiDlgNE\""+_714+"><img id=\"newimg\" src=\"./i/wbox/ne.gif\" style=\"display: block;\"></td>";
html+="</tr>";

html+="<tr width=100% height=\"21px\">";
html+=" <td width=\"8px\" id=\"barw\" class=\"uiDlgW\""+_714+"><img id=\"barwwimg\" src=\"./i/wbox/barw.png\" style=\"display: block;\"></td>";
html+=" <td width=\"100%\" id=\"barn\""+"><img id=\"barnwimg\" src=\"./i/wbox/barn.png\" width=\"100%\" height=\"21px\" style=\"display: block;\"></td>";
html+=" <td width=\"8px\" id=\"bare\" class=\"uiDlgE\""+_714+"><img id=\"barewimg\" src=\"./i/wbox/bare.png\" style=\"display: block;\"></td>";
html+="</tr>";

html+="<tr style=\"width:100%;height:"+bgh+";\">";
html+=" <td width=\"8px\" id=\"w\" class=\"uiDlgW\""+_714+"><img id=\"wwimg\" src=\"./i/wbox/w.png\" height=\"100%\" width=\"8px\" style=\"display: block;\"></td>";
html+=" <td id=\"bg\""+" class=\"uiDlgBg\" width=\"100%\" >&nbsp;</td>";
html+=" <td width=\"8px\" id=\"e\" class=\"uiDlgE\""+_714+"><img id=\"ewimg\" src=\"./i/wbox/e.png\" height=\"100%\" width=\"8px\" style=\"display: block;\"></td>";
html+="</tr>";

html+="<tr width=\"100%\" height=\""+_715+"\">";
html+=" <td id=\"sw\" class=\"uiDlgSW\""+_714+" width=\"8px\" height=\""+_715+"px\">";
html+="<img id=\"swwimg\" src=\"./i/wbox/sw.gif\" height=\""+_715+"\" style=\"display: block;\"></td>";
html+=" <td  id=\"s\" class=\"uiDlgS\""+_714+" width=\"100%\" height=\""+_715+"\">";


  html+="<img id=\"swimg\" src=\"./i/wbox/s.png\" width=\"100%\" height=\""+_715+"\" style=\"display: block;\"></td>";

  html+="<td id=\"sw\" class=\"uiDlgSW\""+_714+" width=\"8px\" height=\""+_715+"px\">";
	html+="<img id=\"sewimg\" src=\"./i/wbox/se.gif\" height=\"100%\" width=\"8px\" style=\"display: block;\">";


	html+="</td></tr></table>";

	this.w_divElement.innerHTML = html;

	this.w_windowFrame=this.w_divElement.getElementsByTagName('table')[0];	//Get our first table id

	var first2=this.w_windowFrame.rows[2].cells[1];
	if(!first2){return;}

	var w = this.w_divElement.offsetWidth-5-5;
	var h = this.w_divElement.offsetHeight-30-6;
	html = "<div id=\"cw"+this.w_divElement.id+"\" style=\"position:absolute;top:6px;right:6px;\"><img id=\"closeimg\" onmousemove=\"this.src = './i/wbox/close_over.gif';\" onmouseout=\"this.src = './i/wbox/close.gif';\" onmousedown=\"this.src = './i/wbox/close.gif';\" onmouseup=\"this.src = './i/wbox/close.gif'; "+"win["+this.winId+"].CloseWindow();\" alt=\"Close window\" title=\"Close window\" src=\"./i/wbox/close.gif\"/></div>";
	html += "<div id=\"w"+this.w_divElement.id+"\" onmousedown=\"return true;\" "+
			"style=\"position:absolute;top:29px;left:4px;border:0px solid;height:"+h+"px;width:"+w+"px;text-align:left;\"></div>"+
			""+
			"";
	first2.innerHTML = html;
};

this.setCaption = function(title){
	if(!this.w_windowFrame){return;}
	this.w_name = title;
	var first1=this.w_windowFrame.rows[1].cells[1];
	if(!first1){return;}

	first1.innerHTML += '<span id="c'+this.w_divElement.id+'">'+title+'</span>';

	var cts = document.getElementById("c"+this.w_divElement.id).style;
	cts.display = 'block';
	cts.position = 'absolute';
	cts.top = '5px';
	cts.left = '8px';
	cts.color = 'white';
	cts.fontfamily = 'Tahoma';
	cts.fontsize = '10px';
	cts.cursor = 'default';

	if(window.addEventListener){
		this.w_divElement.addEventListener('mousedown', this.startDrag, true);
	}else{ // IE
		this.w_divElement.attachEvent('onmousedown', this.startDrag);
	}
};

this.setContext = function(context){
	if(!this.w_windowFrame){return;}

	var first2=this.w_windowFrame.rows[2].cells[1];
	if(!first2){return;}
	
	document.getElementById("w"+this.w_divElement.id).innerHTML = context;
}


this.startDrag = function(evt){
  wiiResetTimer();
	wiiStopFlash();//Stop any new msg title flash

	d('startDrag x:'+this_element.w_divElement.offsetLeft+' y:'+this_element.w_divElement.offsetTop);
	var target;
	var x, y;

	if (isIE)
		target = window.event.srcElement.id;
	else
		target = evt.target.id;//.tagName;
	
	this_element.setActive();

	if (target!='debugwindow') d('target: '+target+' - '+this_element.w_divElement.id);

	switch(target){
		case"nwimg":break;
		case"nwwimg":break;
		case"newimg":break;
		case"barnwimg":break;
		case"barewimg":break;
		case"barwwimg":break;
		case"wwimg":break;
		case"ewimg":break;
		case"swimg":break;
		case"swwimg":break;
		case"sewimg":break;
		case"c"+this_element.w_divElement.id:break;
		case"wt"+this_element.w_divElement.id:break;/* FIXME no drag in FF bug removed */
		case""+this_element.w_divElement.id:break;/* FIXME no drag in FF bug removed */
		case"w"+this_element.w_divElement.id:break;	/*HERE THE PROBLEM??*/
		default:return;
	}
	//d(target);
	//if (target == "TD") return;	//Its not the window frame
	//if (target == "TEXTFIELD") return;
	//if (target == "DIV") return;
	// Get cursor offset from window frame.
	if (isIE) {
		x = window.event.x;
		y = window.event.y;
	} else {
		x = evt.pageX;
		y = evt.pageY;
	}
	xOffset = this_element.w_divElement.offsetLeft-x;
	yOffset = this_element.w_divElement.offsetTop-y;

	// Set opacity
	this_element.setOpacity(this_element.w_divElement,0.8);	// 80% Opacity

	if (isIE) {
		document.onmousemove = this_element.goDrag;
		document.onmouseup   = this_element.stopDrag;

		window.event.cancelBubble = true;
		window.event.returnValue = false;
	} else {

		document.addEventListener('mousemove', this_element.goDrag, true);
		document.addEventListener('mouseup', this_element.stopDrag, true);
		evt.preventDefault();	//Prevent drag AND selection
		evt.stopPropagation();
	}
};

this.goDrag = function(evt){

	var x, y;

	//if (!inMoveDrag) return;

	// Get cursor position - and stop default event action
	if (isIE){
		x = window.event.x;
		y = window.event.y;
		window.event.returnValue = false;
		window.event.cancelBubble = true;
	}else{
		x = evt.pageX;
		y = evt.pageY;
		evt.preventDefault();
		evt.stopPropagation();
	}

	// Move window frame based on offset from cursor.
	this_element.moveWindow(x+xOffset,y+yOffset);
};

this.stopDrag = function(evt){
	d('stopDrag');
	if (isIE){
		document.onmousemove = null;
		document.onmouseup   = null;
	}else{
		document.removeEventListener("mousemove", this_element.goDrag, true);
		document.removeEventListener("mouseup", this_element.stopDrag, true);
	}
	/* Set Opacity back to 100% visible */
	this_element.setOpacity(this_element.w_divElement,1);
};

this.moveWindow = function(x,y){
	//if (x < 0) x = 0;
	if (y < 0) y = 0;

	this.w_divElement.style.left = (x)+'px';
	this.w_divElement.style.top = (y)+'px';
};

this.shakeWindow = function(){
	x=this.w_id.offsetLeft;
	y=this.w_id.offsetTop;

	shakecount = 0;
	this.startShake1();
};

this.startShake1 = function(){
	if (shakecount>10) {
		this.moveWindow(x,y);
		return;
	}
	shakecount++;
	this.moveWindow(x+5,y+0);
	setTimeout("win["+this.winId+"].startShake2()",10);
};

this.startShake2 = function(){
	shakecount++;
	this.moveWindow(x-5,y-0);
	setTimeout("win["+this.winId+"].startShake1()",10);
};

this.CloseWindow = function(){
  if (this.w_name=='Visitors list') return; //No close of Visitor list window
	document.getElementById('wiiapp').removeChild(this.w_divElement);
	d('CloseWindow()');
}

this.setActive = function(){
	if (zindex <= this.w_divElement.style.zIndex){
		zindex = this.w_divElement.style.zIndex++;
	}
	zindex++;
	this.w_divElement.style.zIndex = zindex;
}

this.setOpacity = function(e,val){
	return true;//Disabled for now - too slow on old computers..
	if(e&&e.style){
		var es=e.style;
		if (isIE){
			es.filter = 'alpha(opacity='+val*100+')';	//IE (Also 7?)
		}else{
			es.opacity = val;        //New Mozilla / FireFox / IE7?
			es.MozOpacity = val;     //Old Mozilla / FireFox
			es.KhtmlOpacity = val;   //KHTML rendering engine - Konquerer on Linux - some Safari on MacOS
		}
	}
}

//END CLASS UI
};
