﻿///////////////////////////////////////////////////////////////////
//JavaScript:   jPartChatBox.js
//Description:  ChatBox
//List Definition
//	Default fields to include in default view
//		Title	(plain Title)
//		Created By (Author)
///////////////////////////////////////////////////////////////////
//Notes:
//		If using Title field for remarks, make sure to include plain Title column in default view.  
//		If using Title column with dropdown menu, the field name is LinkTitle.
///////////////////////////////////////////////////////////////////
//Change Log:
//		11/8/2009 Ken - Changed ChatBoxAddMessage message not to use eval
//		12/14/2009 SS - Changed layout to follow jPart template
///////////////////////////////////////////////////////////////////
//field, description, default value
	
myjPart.ShowConfigDefaults = [	
["ID","Unique identifier for plugin","jPartChatBox1"]
,["ChatBoxDiv","HTML Div ID to contain chatbox GUI","jPartChatBoxDiv"]
,["SiteURL","Absolute path to list site location",""]
,["ListName","List name hosting chat","jPartChatBoxList"]
,["ViewName","View to use (blank to use default)",""]
,["MaxDisplay","Number of lines to display","20"]
,["UpdateInterval","Refresh interval in seconds","5"]
,["TimeoutLimit","30 mins = 1800000 ms","1800000"]
,["DisableTimer","Disable timer","false"]
,["Writeable","Textbox is writeable (true by default, false if you want read only view of list)","true"]
,["FieldName","Field name to store message (default is LinkTitle because default list view has hover edit menu)","LinkTitle"]
,["Title","Popup dialog title","Chat Box"]
,["WebPartTitle","webpart title",""]
,["CurrentUser","Current login user",""]
,["ButtonText","Chatbox button title","Open ChatBox"]
,["CAML","Custom CAML", null]
,["ExtWindowUrl","Absolute URL of aspx page to host external chatbox","/src/jPoint/webparts/jPartChatBox.aspx"]
,["DisplayFormat","Color code chat messages, display in table format (color or none)","color"]
,["CallBackFunction","Callback function (optional)",""]    
,["StartMode","Start chatbox mode (INT=inline, EXT=external page,BTN=button)","INT"]    
];

myjPart.setjPartOptions({Plugin:{
	Name:'jPartChatBox'
	, Version:'2.0'
	, Origin:'SharejPoint'
	, Description:'Chat box instant messaging style for SharePoint'
	, Developer:'Ken Le'
}});

//Start Webpart logic code ----------------------------------- 
$(document).ready(function() { //Wait page to load and then apply webpart logic
	if(myjParts[JpartProcessing] != null)
	{
		var thisWebpart = myjParts[JpartProcessing];
		
		BingMapJpartProcessing = JpartProcessing;
		
		try
		{
			//jPart user code goes here ---------------------------
			if (thisWebpart.Options.Local.CallBackFunction != undefined && thisWebpart.Options.Local.CallBackFunction != "")
				window[thisWebpart.Options.Local.CallBackFunction].call();			
			else {
				var jPCB = new jPartChatBox(thisWebpart.Options.Local);	
			}		
			//-----------------------------------------------------
		}catch(err){};
		JpartProcessing = JpartProcessing + 1;
	}
});

//End Webpart logic code -----------------------------------
///////////////////////////////////////////////////////////////////////////////////////////
//Contructor/Class
function jPartChatBox(options)
{
//Default options    
this.defaults = {
};

//Update defaults with user provided options
var thisOpt = $.extend(this.defaults, options);

//Properties
this.FullSiteURL = document.location.protocol + "//" + document.location.host + (thisOpt.SiteURL || jP.valSiteURL());//if thisOpt.SiteURL is not specified, use current siteURL
this.Refresh = true;      //Flag to continue fresh chatbox
this.CurrentUser = "";    //current login user

this.ChatBoxTimeout;        //setTimeout obj
this.WebColor = setWebColor();
this.CurColor = 0;
this.UserColor = {};
this.RecentText = "";   //Track recent message
this.IsOpen = false;

//Methods
this.AddStartButtons = InitChatBoxButtons;
this.OpenExtWindow = InitChatWindow;
this.InitChatBoxGUI = InitChatBoxGUI;

this.InitIntDialog = InitIntDialog;
this.OpenIntDialog = OpenIntDialog;
this.ChatBoxCreateGUI = ChatBoxCreateGUI;
this.ChatBoxGetMessages = ChatBoxGetMessages;
this.ChatBoxAddMessage = ChatBoxAddMessage;
this.ChatBoxTimeoutFunc = ChatBoxTimeoutFunc;
this.ChatBoxTimedUpdates = ChatBoxTimedUpdates;
this.ChatBoxResizeWindow = ChatBoxResizeWindow;
this.ChatBoxOnResize = ChatBoxOnResize;
this.CheckRecent = CheckRecent;
this.ChatBoxClose = ChatBoxClose;
this.NewMsgAlert = NewMsgAlert;

//Init obj to list containing chat messages    
this.spObj = jP.Lists.setSPObject(this.FullSiteURL, thisOpt.ListName);

//Use view if provided
if (thisOpt.ViewName && thisOpt.ViewName != "")
    this.spObj.getSPView(thisOpt.ViewName);

var thisChatBox = this;  

if (thisOpt.StartMode == "INT") this.InitChatBoxGUI();
else if (thisOpt.StartMode == "EXT") this.OpenExtWindow();
else if (thisOpt.StartMode == "BTN") this.AddStartButtons();

  
//CLASS FUNCTIONS
//////////////////////////////////////////////////////////////////////////
//Init GUI, get messages, display dialog
function InitChatBoxGUI() {
    ChatBoxCreateGUI({type:"internal",buttons:false}); //Add gui using code
    ChatBoxGetMessages();
    InitIntDialog(thisOpt.ChatBoxDiv)	//Start timer
}
//Init GUI, add click actions, load messages
function InitChatBoxButtons() {
  $(document).ready(function() {
    thisChatBox.ChatBoxCreateGUI({type:"internal",buttons:true}); //Add gui using code

    //ChatBoxGetMessages();
    //CreateHiddenDialog("OpenChatBoxLink");    
    //$("#"+thisOpt.ID+"ChatterBox").dialog({ autoOpen: false });
    
    $("#"+thisOpt.ID+"OpenChatBoxLink").click(function() {
        thisChatBox.OpenIntDialog("OpenChatBoxLink");
    });
    $("#"+thisOpt.ID+"OpenChatBoxLink2").click(function() {
        thisChatBox.OpenIntDialog("OpenChatBoxLink");
    });
    $("#"+thisOpt.ID+"OpenChatBoxInWindow").click(function() {
        var cbUrl = document.location.protocol + "//" + document.location.host + thisOpt.ExtWindowUrl; 
        //var options = "{Title:\"Dev ChatBox\",ButtonText:\"Button\",SiteURL:\"/eon/dev/chat/\",ListName:\"ChatList\",FieldArray: ['UserName', 'Title'],Debug: false}";
        var options = "{";
        //options += "";
        options += "ID:'"+thisOpt.ID+"'";
        options += ",ChatBoxDiv:'"+thisOpt.ChatBoxDiv+"'";
        options += ",Title:'"+thisOpt.Title+"'";
        options += ",SiteURL:'"+thisOpt.SiteURL+"'";
        options += ",ListName:'"+thisOpt.ListName+"'";
        options += ",FieldName:'"+thisOpt.FieldName+"'";
        options += ",DisplayFormat:'"+thisOpt.DisplayFormat+"'";
        options += ",MaxDisplay:'"+thisOpt.MaxDisplay+"'";
        options += ",UpdateInterval:'"+thisOpt.UpdateInterval+"'";
        options += ",TimeoutLimit:'"+thisOpt.TimeoutLimit+"'";
        options += ",DisplayFormat:'"+thisOpt.DisplayFormat+"'";
        options += ",Writeable:'"+thisOpt.Writeable+"'";
        options += "}";

        cbUrl += "?opts="+options;        
        
        window.open(cbUrl,null,"height=422,width=317,status=0,toolbar=0,menubar=0,location=0,resizable=1");
        //window.open(cbUrl,null,"status=no,toolbar=no,menubar=no,location=no");        
        //OpenExtChatWindow();
    });
  });
}
//Init GUI and open chatbox in external window
function InitChatWindow() {
  $(document).ready(function() {
    thisChatBox.ChatBoxCreateGUI({type:"external",buttons:false}); //Add gui using code
    thisChatBox.ChatBoxGetMessages();
    thisChatBox.ChatBoxTimeout = setTimeout(thisChatBox.ChatBoxTimeoutFunc,parseInt(thisOpt.TimeoutLimit));
    thisChatBox.ChatBoxTimedUpdates();
    thisChatBox.ChatBoxResizeWindow();
    thisChatBox.ChatBoxOnResize();
  });
}
//Init js internal dialog box
function InitIntDialog (LocationDiv) {
    thisChatBox.ChatBoxTimeout = setTimeout(thisChatBox.ChatBoxTimeoutFunc,parseInt(thisOpt.TimeoutLimit));
    thisChatBox.ChatBoxTimedUpdates();
    thisChatBox.IsOpen = false;
}
function CreateHiddenDialog(positionElement) {
    var pos = $("#"+thisOpt.ID+positionElement).offset();
    var boxID = "#"+thisOpt.ID+"ChatterBox";

	//Create dialog
	$(boxID).dialog();

	//Set options
    $(boxID).dialog('option', 'position', [pos.left,pos.top+25]);
    $(boxID).bind("dialogclose", function(event, ui){thisChatBox.ChatBoxClose()});
       
    //Hide dialog for now
    $(boxID).dialog("close");
}
//Open js internal dialog box
/* old
function OpenIntDialog (LocationDiv) {
    var boxID = "#"+thisOpt.ID+"ChatterBox";

	//Open hidden dialog
	$(boxID).dialog("open");

	//hide shadow   
    $(".ui-widget-shadow").css("visibility", "hidden");

	//Start refresh timer
    thisChatBox.ChatBoxTimeout = setTimeout(thisChatBox.ChatBoxTimeoutFunc,parseInt(thisOpt.TimeoutLimit));
    thisChatBox.ChatBoxTimedUpdates();
    thisChatBox.IsOpen = true;
    thisChatBox.NewMsgAlert(false);
}
*/
function OpenIntDialog (LocationDiv) {
    var pos = $("#"+thisOpt.ID+LocationDiv).offset();
    var boxID = "#"+thisOpt.ID+"ChatterBox";
    
    $("#"+thisOpt.ID+"CommentInput").show();

    $(".ui-dialog").remove();
    
	ChatBoxGetMessages();

	//Open hidden dialog
	$(boxID).dialog();
	$(boxID).dialog({ autoOpen: false });	
    $(boxID).dialog('option', 'position', [pos.left,pos.top+25]);
    $(boxID).bind("dialogclose", function(event, ui){thisChatBox.ChatBoxClose()});

	//hide shadow   
    $(".ui-widget-shadow").css("visibility", "hidden");

	//Start refresh timer
    thisChatBox.ChatBoxTimeout = setTimeout(thisChatBox.ChatBoxTimeoutFunc,parseInt(thisOpt.TimeoutLimit));
    thisChatBox.ChatBoxTimedUpdates();
    thisChatBox.IsOpen = true;
    thisChatBox.NewMsgAlert(false);
}

//Add new message to list
function ChatBoxAddMessage() {
	var newmsg = $("#"+thisOpt.ID+'CommentInput').val();
	if (newmsg == "") return;
	$("#"+thisOpt.ID+'CommentInput').val("")
   
    //Add new item to list
   	var row = {};
    if (thisOpt.FieldName != "" && thisOpt.FieldName != "LinkTitle" /*LinkTitle cannot be written to*/) {
    	row[thisOpt.FieldName] = newmsg;
    }	
    else {
    	row["Title"] = newmsg;
    }
    var newentry = [row];
    thisChatBox.spObj.addItem(newentry);

	//Get list items
    thisChatBox.ChatBoxGetMessages(true);

	//Reset refresh timer
    thisChatBox.Refresh = true;
    clearTimeout(thisChatBox.ChatBoxTimeout); 
    thisChatBox.ChatBoxTimeout = setTimeout(thisChatBox.ChatBoxTimeoutFunc,parseInt(thisOpt.TimeoutLimit));

}
//Retrieve messages from list
function ChatBoxGetMessages(added)
{
    //Set up chatterbox object
    //chatterbox.getSPView('Recent');
    var chatterbox = thisChatBox.spObj;

    //If not using view, then use default caml
    if (thisOpt.ViewName == undefined || thisOpt.ViewName == "")
    {    
        //get chat list data
        var qry = "<OrderBy><FieldRef Name='ID' Ascending='FALSE' /></OrderBy>";
        chatterbox.getSPItemsWithQuery(qry, thisOpt.MaxDisplay);
    }
    
	//Reverse order    
    var data = jQuery.makeArray(chatterbox.JQueryData);
    data.reverse();
    
    var names = ['Author','LinkTitle'];
    if (thisOpt.FieldName != "") {
    	names[1] = thisOpt.FieldName;
    }    
   
    if (thisOpt.DisplayFormat == "color")
        DisplayData(data, names, thisOpt.ID+'EONChatMsgDiv');
    else
    {
        chatterbox.drawTable(data, names, 'ChatMsgs');

        //Modify table layout
        $(function(){
            $('#"+thisOpt.ID+"ChatMsgs tr:even').addClass("evenrow");
            $('#"+thisOpt.ID+"ChatMsgs tr:odd').addClass("oddrow");
            $(".oddrow").css("background","#ecf6fc");
            $(".oddrow").css("font-family","Tahoma, sans-serif");
            $(".oddrow").css("font-size","9pt");
            $(".evenrow").css("font-family","Tahoma, sans-serif");
            $(".evenrow").css("font-size","9pt");
        });
    }
    thisChatBox.Refresh = true;
    thisChatBox.CheckRecent(data, added);
}
//Check if enter key was pressed and add new message
function ChatBoxCheckEnter (e){
   var characterCode
   if(e && e.which){
      e = e
      characterCode = e.which
   }
   else{
      e = event
      characterCode = e.keyCode
      Log(characterCode)
   }
   if(characterCode == 13){
      thisChatBox.ChatBoxAddMessage();
      return false
   }
   else{
      return true
   }
}

// Initial update and start the timer
// If "ChatBoxRefresh" is set to false, keep using the timer but don't actually update the content
function ChatBoxTimedUpdates() {
	if (thisChatBox.Refresh) {
      	thisChatBox.ChatBoxGetMessages();
   	}
   	if (!thisOpt.ChatBoxDisabled) {
   		setTimeout(thisChatBox.ChatBoxTimedUpdates, parseInt(thisOpt.UpdateInterval) * 1000);
   	}
}

// Disable input box if the timeout timer fires
function ChatBoxTimeoutFunc() {
    thisOpt.ChatBoxDisabled = true;
    thisChatBox.Refresh = false;
    if (thisOpt.Writeable == "true") {
        $('#'+thisOpt.ID+'CommentInput').css("visibility", "hidden");
    }
    $("#"+thisOpt.ID+"StatusDiv").html("<font color=maroon>Timed out due to inactivity. Reopen to rejoin.</font>");
}

//Create DOM element
function ChatBoxCreateElement(parent, type, id, classname) {
  var elem = document.createElement(type);
  if (id)
    elem.setAttribute("id", id);
  if (classname)
    elem.setAttribute("className", classname);
  parent.appendChild(elem);
  return elem;
}
//Create DOM input element
function ChatBoxCreateInputElement(parent, type, /* optional */ id) {
  var elem = document.createElement('input');
  elem.setAttribute('type', type);
  if (id)
    elem.setAttribute('id', id);
  parent.appendChild(elem);
  return elem;
}
//Create chatbox GUI
//opt.type - internal or external
//opt.buttons - true or false
function ChatBoxCreateGUI(opt) {
    var maindiv = $("#"+thisOpt.ChatBoxDiv);
    if (maindiv.length == 0)
    	maindiv = $(document.body).append("<div id='"+thisOpt.ID+"jPartChatBoxDiv"+"' />")
    
    if (opt.type=="internal" && opt.buttons) {
        var h = "";
        //h += "<div id='"+thisOpt.ID+"ChatterButtonDiv"+"' 
        //style='{position:absolute;top:0;left:500;cursor:hand}'>";
        var btnleft = calcButtonPosition();
        h += "<div id='"+thisOpt.ID+"ChatterButtonDiv"+"' "
        	+ "class=\"ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix\" "
        	//+ "style='{position:absolute;top:0;left:"+btnleft+";cursor:pointer;}'"
        	+ ">";
        var btncss = {
        	'position':'absolute',
        	'top':'0',
        	'left':btnleft,
        	'cursor':'pointer'
        } 
        h += "<span id='"+thisOpt.ID+"ChatterLink"+"' >";
        h += "<table>"
        	+"<tr>"
        	+"<td><span id='"+thisOpt.ID+"OpenChatBoxLink"+"' class='ui-icon ui-icon-comment'></span></td>"        
        	+"<td><span id='"+thisOpt.ID+"OpenChatBoxLink2"+"' style='{font-family:Tahoma; san-serif;font-size:9pt}'>"+thisOpt.ButtonText+"</span></td>"        
        	+"<td><span id='"+thisOpt.ID+"OpenChatBoxInWindow"+"' class='ui-icon ui-icon-extlink' title='Open in saparate window'></span></td>"        
        	+"</tr>"
        	+"</table>";
        h += "</span></div>"
        maindiv.append(h);
        $("#"+thisOpt.ID+"ChatterButtonDiv").css(btncss)
    }
    //<!-- ChatBox container -->
    maindiv.append("<div id='"+thisOpt.ID+"ChatterBox"+"' title='"+thisOpt.Title+"' />");
    var ChatterBox = $("#"+thisOpt.ID+"ChatterBox")

    if (thisOpt.DisplayFormat == "color")
    	ChatterBox.append("<div id='"+thisOpt.ID+"EONChatMsgDiv"+"' />")
    else
        CreateChatBoxHTMLTable(ChatterBox.get(0),opt);
       
    if (thisOpt.Writeable == "true") {
        ChatterBox.append("<input type='text' id='"+thisOpt.ID+"CommentInput"+"' "
        	+ "maxlength='256' title='Enter message' "
        	+ "/>");
        $("#"+thisOpt.ID+"CommentInput").keypress(function (e) {
            ChatBoxCheckEnter(e);
        });
        var inputcss = {
        	'width':'100%'
        };
        $("#"+thisOpt.ID+"CommentInput").css(inputcss); //compatible with chrome
        if (opt.type=="internal" && opt.buttons)
        	$("#"+thisOpt.ID+"CommentInput").hide();
    }
    ChatterBox.append("<div id='"+thisOpt.ID+"StatusDiv"+"' />")
}
function CreateChatBoxHTMLTable(ChatterBox, opt) {
    //    <table id="ChatMsgs" width="100%" cellpadding=0 cellspacing=0>
    //<tbody>
    //<tr>
    //<td class="field[Username]" width="1px"></td>
    //<td>&nbsp;&nbsp;</td><td class="field[LinkTitle]" width="90%"></td>
    //</tr>
    //</tbody>
    //</table>
    //    <input type="text" id="CommentInput" style="Width:100%" maxlength="256" title="Enter message"  onKeyPress="ChatBoxCheckEnter(event)" />
    //    <div id="StatusDiv"></div>
    var table2 = ChatBoxCreateElement(ChatterBox, "table", thisOpt.ID+"ChatMsgs");
    if (opt.type=="internal")
        table2.setAttribute("width", "100%");
    else
        table2.setAttribute("width", "97%");
    table2.setAttribute("cellPadding", 0);
    table2.setAttribute("cellSpacing", 0);
    table2.setAttribute("align", "center");
    var tbody2 = ChatBoxCreateElement(table2, "tbody");
    var tr2 = ChatBoxCreateElement(tbody2, "tr");

    //Use array of fields if provided
    if (thisOpt.FieldArray != null) {
        for(var f=0; f<thisOpt.FieldArray.length; f++) {
            var tda2 = ChatBoxCreateElement(tr2, "td");
            tda2.innerHTML = "&nbsp;&nbsp;";
            var tda1 = ChatBoxCreateElement(tr2, "td");
            tda1.setAttribute("className", "field["+thisOpt.FieldArray[f]+"]");
        }
    }
    else {
        var td21 = ChatBoxCreateElement(tr2, "td");
        td21.setAttribute("className", "field[Username]");
        td21.setAttribute("width", "1px");
        var td22 = ChatBoxCreateElement(tr2, "td");
        td22.innerHTML = "&nbsp;&nbsp;";
        var td23 = ChatBoxCreateElement(tr2, "td");
        td23.setAttribute("className", "field[LinkTitle]");
        td23.setAttribute("width", "90%");
    }
}
//Resize window
function ChatBoxResizeWindow() {
    var cb = $("#jPartExtChatBox");
  
    if ($.browser.msie) {
	    if (thisOpt.DisplayFormat == "color")
	        window.resizeTo(cb.width()+25, cb.height()+110);
	    else
	        window.resizeTo(cb.width()+25, cb.height()+110);
    }
    else {
	    if (thisOpt.DisplayFormat == "color")
	        window.resizeTo(cb.width()+50, cb.height()+110);
	    else
	        window.resizeTo(cb.width()+50, cb.height()+110);
    }
}
//Determine position for button
function calcButtonPosition() {
    if ($.browser.msie) {
	    var h = document.body.clientHeight;
	    var w = document.body.clientWidth;
	}
	else {
	    var h = $(document).height();
    	var w = $(document).width();
	}
	return w/2;
}
//Resize chatbox dialog
function ChatBoxOnResize() {
    //resize ChatterBox div
    var cb = $("#"+thisOpt.ID+"ChatterBox");
    if ($.browser.msie) {
	    var h = document.body.clientHeight;
	    var w = document.body.clientWidth;
	    cb.dialog("option", 'width', w+3);
	}    //cb.dialog("option", 'height', h);
	else {
	    var h = $(document).height();
    	var w = $(document).width();

	    cb.dialog("option", 'width', w+3);
	}
    
    //resize message table and input box
    var dia = $(".ui-dialog"); 
    if ($.browser.msie) {
	    $("#"+thisOpt.ID+"ChatMsgs").width(dia.width()-28)
	    $("#"+thisOpt.ID+"CommentInput").width(dia.width()-35)
	}
    else {
	    $("#"+thisOpt.ID+"ChatMsgs").width(dia.width()-35)
	    $("#"+thisOpt.ID+"CommentInput").width(dia.width()-45)
	}
}
function ChatBoxClose() {
    thisChatBox.IsOpen = false;
}
function DebugMsg(msg) {
    if (thisOpt.Debug) $.log(msg, 0);
}
function DisplayData(data, names, divid) {
    //$(data).log("Data");
    var out = "<table cellspacing=0 cellpadding=0>";
    var cuser = "";
    var ucolor = {};   
	$.each(data, function(i, row){
		var trow = "";
	    //$(row).log();
	    var attrs = $(row).get(0).attributes;
	    //var user = getAttrValue(attrs, "username");
	    //var msg = getAttrValue(attrs, "title");
	    var user = getAttrValue(attrs, names[0]);
	    var msg = getAttrValue(attrs, names[1]);
	    if (user.indexOf(";#")>-1) 
	    	user = user.substr(user.indexOf(";#")+2);
	    var suser = user.replace(/[^a-zA-Z0-9]+/g,'');
	    var created = getAttrValue(attrs, "created");
        var color = thisChatBox.UserColor[user];
	    if (user != cuser)
	    {
	        //Log(user +" " + color)
	        if (typeof color == "undefined")
	        {
	            thisChatBox.UserColor[user] = thisChatBox.CurColor;
	            color = thisChatBox.CurColor;
	            thisChatBox.CurColor++;
	        }
    		ucolor[suser] = thisChatBox.WebColor[color];
	        //out += "<tr><td colspan=2 class='user' style='{color:"+thisChatBox.WebColor[color]+"}'>"+user+ "  ["+created.substr(5,11)+"] "+thisChatBox.WebColor[color]+"</td></tr>";
	        out += "<tr><td colspan=2 class='user"+suser+"' >"+user+ "  ["+created.substr(5,11)+"]</td></tr>";
	        cuser = user;
	    }    
	    out += "<tr><td class='msg"+suser+"'>&nbsp;&nbsp;</td>";
	    out += "<td class='msg"+suser+"' >"+msg+"</td></tr>";
    });
    out += "</table>";
    $("#"+divid).html(out);
    
	//<span class='ui-icon ui-icon-triangle-1-e' />
	$.each(ucolor, function(n, v) {
		//alert(n + "|"+v);
	    var cssUser = {
	        'font-size' : '8pt'
	        ,'color' : ucolor[n]
	    }
	    var cssMsg = {
	        'font-weight' : 'bold'
	        ,'font-size' : '8pt'
	        ,'color' : ucolor[n]
	    }
    	$(".user"+n).css(cssUser);
    	$(".msg"+n).css(cssMsg);
    });
    //$(".msg").addClass("ui-icon ui-icon-triangle-1-e")
    //Log(out)

}
function getAttrValue(attrs, attr) {
    var res = "";
        attr = attr.toUpperCase();
    $(attrs).each(function(j, attrItem){
	    var	attrName = this.name.replace(/ows_/i, "").replace(/_/, "").toUpperCase();
	    var attrValue = this.value;
		if(attrName == attr)
		    //res = escape(attrValue.replace(/[\r\n]/g,""));
		    res = attrValue.replace(/[\r\n]/g,"");
    });
    return res;
}
function setWebColor() {
    return [
    'CadetBlue'
    ,'Brown'
    ,'Blue'
    ,'Chocolate'
    ,'CornflowerBlue'
    ,'Crimson'
    ,'DarkBlue' 
    ,'DarkCyan' 
    ,'DarkGreen' 
    ,'Darkorange' 
    ,'DarkRed'
    ,'DarkSlateBlue'
    ,'DarkViolet'
    ,'FireBrick'
    ,'GoldenRod'
    ,'Green'
    ,'LightSeaGreen'
    ,'MediumSlateBlue'
    ,'Navy'
    ,'RoyalBlue'
    ,'SeaGreen'
    ,'SlateBlue' 
    ,'BlueViolet'
    ,'SteelBlue'
    ,'OrangeRed'
    ,'Teal'
    ,'Tomato' 
    ]
}
function CheckRecent(data, added) {
	if (data.length == 0) {
		thisChatBox.RecentText = "";
		return;
	}
    var attrs = data[data.length-1].attributes;
    var user = getAttrValue(attrs, "username");
    var msg = getAttrValue(attrs, "title");
    var created = getAttrValue(attrs, "created");
    var recent = user + "|" + msg;
    if (thisChatBox.RecentText == "") {
        thisChatBox.RecentText = recent;
    }    
    else if (added==undefined && thisChatBox.RecentText != recent) {
        thisChatBox.NewMsgAlert(true);
        thisChatBox.RecentText = recent;
    }
    else if (added==true) {
        thisChatBox.RecentText = recent;
    }
    else {
        //$("#OpenChatBoxLink2").css("text-decoration","none";
    }    
}
function NewMsgAlert(on) {
    //SetAlertStyle("ui-dialog-title-ChatterBox", on)
    SetAlertStyle(thisOpt.ID+"OpenChatBoxLink2", on)
}
function SetAlertStyle(div, on)
{
    if (on) {
        $("#"+div).css("color","orange");
        $("#"+div).css("font-weight","bold");

        if (thisOpt.WebPartTitle != "") {
            var hdr = $("H3 SPAN:contains('"+thisOpt.WebPartTitle+"')");
            if (hdr.length > 0) {
	            var text = hdr.html();
	            if (text.indexOf("New message")<0) {
	                var newmsg = " <span id="+thisOpt.ID+"ChatBoxNewMsg>(New message!)</span>";
	                hdr.html(text + newmsg)
	                $("#"+thisOpt.ID+"ChatBoxNewMsg").css("color", "orange");
	                $("#"+thisOpt.ID+"ChatBoxNewMsg").css("font-weight","bold");
	                $("#"+thisOpt.ID+"ChatBoxNewMsg").click(function() {
	                    NewMsgAlert(false);
	                });
	                $("#"+thisOpt.ID+"ChatBoxNewMsg").css("cursor", "hand");
	            }
            }
        }
    }        
    else {
        $("#"+div).css("color","black");
        $("#"+div).css("font-weight","normal");
        
        if (thisOpt.WebPartTitle != "")
            $("H3 SPAN:contains('"+thisOpt.WebPartTitle+"')").html(thisOpt.WebPartTitle);

    }
}
function OpenExtChatWindow() {
    //TBD - needs work
    var pgtx = "";
    pgtx += '<html xmlns="http://www.w3.org/1999/xhtml" >\r\n';
    pgtx += '<head runat="server">\r\n';
    pgtx += '<title>EONChatBox</title>\r\n';
    //pgtx += '<script type="text/javascript" src="/eon/com/res/jquery.js"></script>\r\n';
    //pgtx += '<script type="text/javascript" src="/eonapp/eonutils/EONChatBox.js"></script>\r\n';
    pgtx += '<script>\r\n';
    pgtx += '   $(document).ready(function() {\r\n';
    pgtx += '      var chatbox = new EONChatBox({\r\n';
    pgtx += '        Title:"Dev ChatBox"\r\n';
    pgtx += '        ,SiteURL:"/eon/dev/chat/"\r\n';
    pgtx += '        ,ListName:"ChatList"\r\n';
    pgtx += "        ,FieldArray: ['UserName', 'Title']\r\n";
    pgtx += '        ,Debug: false\r\n';
    pgtx += '      });\r\n';
    pgtx += '        chatbox.OpenExtWindow();\r\n';
    pgtx += '   });\r\n';
    pgtx += '    </script>\r\n';
    pgtx += '</head>\r\n';
    pgtx += '<body onresize="ChatBoxOnResize()">\r\n';
    pgtx += '    <form id="form1" runat="server">\r\n';
    pgtx += '    </form>\r\n';
    pgtx += '</body>\r\n';
    pgtx += '</html>\r\n';
    var win = window.open("",null,"height=422,width=317,status=no,toolbar=no,menubar=no,location=no,resizable=1");
    win.document.write('<script type="text/javascript" src="/eon/com/res/jquery.js"></script>\r\n');
    win.document.write(pgtx);
    //win.document.refresh();
}


}//End CLASS EONChatBox


