﻿var user = null;
var friends = null;
var friendsByUID = null;
var friendsBySNUID = null;
var friendIDs = new Array();
var friendSigs = new Array();
var friendIDsStr = null;
var friendSigsStr = null;
var recentMsgs = null;
var friendsMsgs = null;
var friendsTimestamp = null;
var UIDSig = null;;
var UIDStamp = null;;
var updateTimer = null;
var lastResetTime = 0;
var lastMsgTime = 0;
var nextTS = 0;
var TSArray = new Array();
var canNotify = false;
var loggedInToMsgServer = false;

var publicMsgTemplate = null;
var publicDiv = null;;
var privateDiv = null;;
var traceDiv = null;;
var notificationShown = false;
var showingNotificationUI = false;
var privateMsgCount = 0;
var updatesCounter = 0;
var currentMsgDiv = null;
var providers = new Array();
var loginProvider;
var connectedAtStartup = false;

var twitterBaseURL = "http://search.twitter.com/search.json";
var twitterRefreshParams = null;
var twitterUpdateTimer = null;
var twitterMaxFill = -1;
var twitterriends = -1;

var conf=
{
	APIKey:APIKey,
	signIDs:true,
	enabledProviders:"myspace,facebook,twitter,Yahoo"
}

function onBodyLoad()
{
	publicMsgTemplate = new Template ($('txtPublicMsgTmp').value);

	publicDiv = $('divPublicMessages');
	
	/*
	if (!showPublicChat)
	    $('divPublicMessages').hide();
	   */
	
	privateDiv = $('divPrivateMessages');
	traceDiv = $('divTrace');
	
	if (traceEnabled)
		$('tabTrace').show();

    ///get enabled privders from querystring.
    conf.enabledProviders = enabledProviders || conf.enabledProviders;

	var time = new Date().getTime();
	$('pixel').src="http://counters.gigya.com/wildfire/pimp.ashx?name=WBP&m=0&g=0&d="+eventID+"&p="+partnerID+"&l="+time+"&pt="+time+"&CXNID=2000002.0NXC";

    doResize();
	showTab('public');
	gigya.services.socialize.addEventHandlers(conf, { onLogin:onGSLogin, onLogout:showLoginUI}   ); 		
	getUserInfo();
	getRecentMsgs();
	
}

function getUserInfo()
{
	gigya.services.socialize.getUserInfo(conf,{callback:getUserInfo_CB});	    
}

function getUserInfo_CB(res)
{
	
	trace("getUserInfo_CB",Object.toJSON(res));
	
	if (res.status==undefined || res.status!="OK")
	{
		retry("getUserInfo()");
		return;
	}
	user = res.user;
	if (!isLoggedIn(user))
	{
		showLoginUI();
	} else
	{
		connectedAtStartup = true;
		onGSLogin();
	}
}

function isLoggedIn(u)
{
	return (u!=null) && (u.identities!=undefined) && (u.identities!=null) && (u.identities[u.loginProvider]!=undefined);
}

function getUserPhoto(u)
{
	if (u.thumbnailURL!="")
	{
		return u.thumbnailURL;
	}
	else if (u.photoURL!="")
	{
		return u.photoURL;
	}
	else {
		return "images/JonDoe_40X40.gif";
	}

}
function onGSLogin(res)
{
	trace("onGSLogin",Object.toJSON(res));
	if (res)
	{
	    
		user = res.user;
		if (user==null || !user.isLoggedIn)
		{
			showLoginUI();
			return;
		} else{
		    ///successful login.
		    if(!showPublicChat)
		        progress.show();
			user.UIDSig = res.signature;
			user.timestamp = res.timestamp;
		}
    }
    
    providers = new Array();
    
    for (var p in user.identities)
        providers.push(p);
    trace("user connected to "+providers.join(","));
	canNotify =  user!=null && user.capabilities.notifications;
	$('txtMsg').value = textboxWatermark;
	$('txtMsg').style.color="silver";
	$('chkPublic').checked = sendToAllDefVal;
	$('divLoggedIn').show();
	$('btnUpdate').disabled = true;
	$('divLogin').hide();
	$('tabConnect').show();
	$('txtName').update(user.nickname);
	$('imgUser').src = getUserPhoto(user);
	$('imgUser').show();
	
	showConnectUI();
	getFriends();

	loginProvider = getProvider(user);
	if (connectedAtStartup)
	    report('autoLogin_' + loginProvider);
    else
        report('newLogin_' + loginProvider);

    if (setStatusOnLogin)
        setStatus(defaultStatusMsg);
}


function setStatus(msg,suffix)
{
    trace("setStatus", msg);
    var isConnectedToFacebook = providers.include("facebook");
    var comma = "";
    var params = {status:msg};

    var clonedConf = Object.clone(conf);
    clonedConf.enabledProviders = "";
    var networks = [];
    if(suffix!=undefined)
    {
        params.status = msg + suffix;
        for (var i=0; i<providers.length; i++)
        {
            var provider = providers[i].toLowerCase();
            switch(provider) 
            {
                /* RAVIV: REMOVED TO SEND SUFFIX TO FACEBOOK
                case "facebook":
                    continue;
                break;
                */
                default:
                    if(provider == "twitter" && params.status.length >= 140)
                        continue;
                        
                    networks.push(provider);
                    clonedConf.enabledProviders += comma + providers[i];
                    comma = ", "
                break;
            }
        }
        
        ///make sure we dont set status if we dont have enabled providers.
        if(clonedConf.enabledProviders == "" && !isConnectedToFacebook)return;
        
    }
    
    //send to all enabled providers (not including twitter and facebook) + suffix.
    if(clonedConf.enabledProviders.length>0)
    {
	    gigya.services.socialize.setStatus(clonedConf,params);
	}

	///send to facebook without suffix.
	/* RAVIV: REMOVED TO SEND SUFFIX TO FACEBOOK
	if(isConnectedToFacebook)
	{
	networks.push('facebook');
	clonedConf.enabledProviders = "facebook";
	gigya.services.socialize.setStatus(clonedConf,{status:msg});
	}*/
	
    for (var i=0; i<networks.length; i++)
	    report("setStatus_" + networks[i]);
}

function report(event) {
    var img = new Image();
    trace("reporting event", event);
    img.src = 'http://counters.gigya.com/wildfire/pimp.ashx?name=CEVT&enc=0&evt=' + event + '&pid=' + partnerID + "&cid=" + eventID + "&buster=" + new Date().getTime();
}


function showConnectUI()
{
	trace("showConnectUI",null);
	var params=
	{
		containerID:"divConnect",
		showTermsLink: false,
		showEditLink: false,
		hideGigyaLink: true,
		height:25,
		width:100,
		UIConfig:connectUIConfig,
		onError:function() {retry("showConnectUI()");}
	}
	
	gigya.services.socialize.showConnectUI(conf,params);
	gigya.services.socialize.addEventHandlers(conf, { onConnect:onNetworkAdded}   ); 		
}

function onNetworkAdded(res)
{
    trace("onNetworkAdded", Object.toJSON(res));

    for (var p in res.user.identities) {
        if (!providers.contains(p)) {
            providers.push(p);
            report("connect_" + p);
        }
    }
            
    if (setStatusOnLogin)
        setStatus(defaultStatusMsg);
	getFriends();
}

function getFriends()
{
	gigya.services.socialize.getFriendsInfo(conf,{callback:getFriendsInfo_CB} ); 
}


function getFriendsInfo_CB(res)
{
	trace("getFriendsInfo_CB",Object.toJSON(res));
	
	if (res.status==undefined || res.status!="OK")
	{
		retry("getFriends()");
		return;
	}
	
	if (res.friends==undefined) 
	{
		trace("getFriendsInfo_CB","ERROR: res.friends==undefined");
		return;
	}
	
	friends = res.friends.asArray(); 
	friendIDs = new Array();
	friendsByUID = {};
	friendsBySNUID = {};
	friends.each( 
		function(f) 
		{ 
			try {
				friendIDs.push(f.UID); 
				friendSigs.push(f.friendshipSig); 
				friendsByUID[f.UID] = f;
				friendsTimestamp = f.timestamp;
				for (provider in f.identities)
				{
					friendsBySNUID[provider+f.identities[provider].providerUID] = f;
				}
			} catch (e)
			{
				trace("getFriendsInfo_CB","ERROR: Error processing friend. error="+e.message+". f="+Object.toJSON(f));
			}
			//trace(f.UID, f.nickname);
		} 
	);
	friendIDsStr = friendIDs.join(',');
	friendSigsStr = friendSigs.join(',');
	loginToMsgSrv();
}

function loginToMsgSrv()
{
	new Ajax.Request('API.ashx?f=l',  {
		method:'post', 
		parameters: {
			e:eventID, 
			ui:user.UID, 
			uis: user.UIDSig, 
			ts: user.timestamp, 
			un: user.nickname, 
			pu: user.profileURL,
			up: getUserPhoto(user),
			fr: friendIDsStr, 
			frs: friendSigsStr,
			fts: friendsTimestamp,
			n:user.loginProvider},
		onSuccess:loginToMsgSrv_CB, 
		onFailure: function(res){ ajaxFail('loginMsgSrv',res); }
	});
}	    

function loginToMsgSrv_CB(res)
{
    if(!showPublicChat)
        progress.hide();
        
    var tab = $('tabPrivate');
	tab.show();

	if($$("#tabs td.selected").length==0)
	{
	    showTab('private');
	}
	
	loggedInToMsgServer = true;
	$('btnUpdate').disabled = false;
	trace('loginToMsgSrv_CB',res.responseText);
	trace('loginToMsgSrv_CB',"connectedAtStartup="+connectedAtStartup);
	getMsgHistory();
}

function logoutFromMsgSrv()
{
	new Ajax.Request('API.ashx?f=o&e='+eventID);
}	    

function getMsgHistory()
{
	trace('getMsgHistory','');
	new Ajax.Request('API.ashx?f=h',  {
		method:'post', 
		parameters: {e:eventID},
		onSuccess:getMsgHistory_CB, 
		onFailure: function(res){ ajaxFail('getFriendsMsg',res); }
	});
}

function getMsgHistory_CB(res)
{
	trace('getMsgHistory_CB',res.responseText);
	eval("msgArray = "+res.responseText);
	
	if (msgArray.ma.length>0)
	{
		msgArray.ma.reverse(false).each(
			function(msg)
			{
				renderMsg(msg,true)
			}
		);
	}	
	if (!notificationShown && msgArray.ma.length == 0)
	{
		if (canNotify && !showingNotificationUI)
			showNotificationUI();
		else
			showFeedback("No Updates from friends yet.");
    }
    if ($$("#tabs td.selected").length == 0) {
        showTab('private');
    }
	
}
/*
function getLastMsgTime()
{
  	if (recentMsgs!=null  && recentMsgs.length >0)
		return recentMsgs.first().t;
	else
		return 0;
}*/

function getRecentMsgs()
{
    
    if(showPublicChat || (!showPublicChat && (user != null && user.isLoggedIn)))
    {
	    new Ajax.Request('API.ashx?f=u',  {
		    method:'post', 
		    parameters: {e:eventID, l:nextTS},
		    onSuccess:getRecentMsgs_CB, 
		    onFailure: function(res){ retry("getRecentMsgs()"); }
	    });
	}
	else{
	    getRecentMsgs_CB(null);
	}
	
}
function getRecentMsgs_CB(res)
{
	try {
		updatesCounter++;
		var isFirstTime = (updatesCounter==1);
		var resData  = null;

		try {
			eval("resData = "+res.responseText);
		} catch(e){
			// error parsin response, might be problematic msg, try to skip a few
			trace("getRecentMsgs_CB","ERROR: Unable to parse response. error="+e.message+". responseText="+res.responseText);
			nextTS += 1000;
			updateTimer = setTimeout("getRecentMsgs()",updateIntervalMS);
			return;
		}

		if (resData!=null )
		{
			var resetTime = resData.f;
			lastMsgTime =  resData.t;
			var shouldReset = resetTime>lastResetTime && resetTime>=lastMsgTime;
			//trace("getRecentMsgs_CB",Object.toJSON(resData)+"<br>resetTime="+resetTime+", lastResetTime="+lastResetTime+", lastMsgTime="+lastMsgTime);						
		
			var gotMsgs = resData.ma!=null && resData.ma.length>0;
			
			if (shouldReset)
			{
				trace("getRecentMsgs_CB", "Got reset from server. resetTime="+resetTime+", lastResetTime="+lastResetTime);
				publicDiv.update("");
				lastResetTime = resetTime;
			}
			
			if (gotMsgs)
			{
				trace('getRecentMsgs_CB',res.responseText);
				recentMsgs = resData.ma;
				recentMsgs.reverse(false).each(
					function(msg)
					{
						var fromSelf = isLoggedIn(user) && msg.u == user.UID
						if ( !fromSelf || isFirstTime)
						{
							renderMsg(msg,false)
						}
					}
				);
			}
			TSArray.push(lastMsgTime);			
			if (TSArray.length==KEEP_MSG_TIME_EVERY)
			{
				nextTS = TSArray.shift();
			} else {
				nextTS = TSArray[TSArray.length-1];
			}
		}
	} catch (e)
	{
		trace("getRecentMsgs_CB","ERROR: "+e.message);
	}
	
	updateTimer = setTimeout("getRecentMsgs()",updateIntervalMS);	
	getTweets();
	
}

function showFeedback(msg)
{
	var div = new Element("div");
	div.id = "notificationFeedback";
	div.update("<br><br>"+msg);
	privateDiv.insert({top:div});
	setTimeout("$('notificationFeedback').remove()",2000);
}

function showNotificationUI()
{
	notificationShown = true;
	showingNotificationUI = true;
	var params=
	{	
		containerID:"divSendNotification",
		showEditLink:false,
		hideGigyaLink:true,
		width:290,
		height:280,
		onSelectionDone:onSelectionDone,
		onClose:
			function(res) 
			{
				privateDiv.update("");
				showingNotificationUI = false;
			},
		UIConfig:selectorUIConfig
	}
	
	privateDiv.update("<div id='friendSelectorTitle'>No friends watching yet? Invite them now!</div><div id='divSendNotification'></div>");
	gigya.services.socialize.showFriendSelectorUI(conf, params);
}

function onSelectionDone(res)
{
	privateDiv.update("");
	showingNotificationUI = false;
	// SendNotification
	var subject = notificationTitle;
	var body = notificationBody;
	if (res.friends.getSize() > 0)
	{
	    var params = 
	    {
	        //callback:sendNotification_CB,
	        subject:notificationTitle,
	        body:body,
	        recipients:res.friends
	    };
		gigya.services.socialize.sendNotification(conf, params)
		showFeedback("Notification sent.");
	}
	
}

function getUserByID(id)
{
	if (user!=null && id == user.UID)
		return user;
	else if (friendsByUID!=null)
		return friendsByUID[id];
	else
		return null;
}

function formatTime(intTime)
{
	var d = new Date();
	d.setTime(intTime);
	var hour = d.getHours();
	var minute = d.getMinutes();
	var ap = "AM";
   if (hour   > 11) { ap = "PM";             }
   if (hour   > 12) { hour = hour - 12;      }
   if (hour   == 0) { hour = 12;             }
   if (hour   < 10) { hour   = "0" + hour;   }
   if (minute < 10) { minute = "0" + minute; }
	
	return hour+":"+minute+" "+ap;
}
function getProvider(u)
{
	if (u==null) return "";
	
	if (u.provider!=undefined) return u.provider;
	if (u.loginProvider!=undefined) return u.loginProvider;
	if (u.identities[0]!=undefined) return u.identities[0].provider;
	
	for (key in u.identities)
		if (u.identities[key]!=undefined) return u.identities[key].provider;
		
	return "";	
}

function renderMsg(msg, showOnlyInPrivate)
{
	try{
		// remove HTML tags
		msg.formattedMsg = msg.m.replace(/(<([^>]+)>)/ig,"");  // remove html tags
		msg.escapedMsg = escape(msg.m);
		//msg.formattedMsg = renderTwitterNames(msg.formattedMsg, "<span class='msgSender'>@#{username}</span>");

		// convert time to string
		msg.timeStr = formatTime(msg.t);
		
		// adjust image frame offet
		if (isIE())
			msg.photoFrameOffset = "-43";
		else
			msg.photoFrameOffset = "-40";
			
		// fill missing details from private msgs
		if (!msg.p)
		{
			var u = getUserByID(msg.u);
			if (u!=null)
			{
				msg.up = getUserPhoto(u);
				msg.un = u.nickname;
				msg.n = getProvider(u);
				msg.pu = u.profileURL;
			}
		}
		
		///normalize username for javascript.
		msg.eun = normalizeUsername(msg.un);
		
		if (msg.pu!=null && msg.pu.indexOf("myspace.com")!=-1)
			msg.pu += "?utm_source=Gigya_TNT&utm_medium=MID& &utm_campaign=NBAECF";

		// show reply icon only if I'm conenct to twitter and msg from twitter user
		var canReply = user!=null && user.identities['twitter']!=undefined && msg.n=='twitter';
		if (canReply)
			msg.replyDisplay="block";
		else
			msg.replyDisplay="none";
		
		// msg.providerUID is filled only when msg from external source (twitter)
		var fromFriend = friends!=null && (friendsByUID[msg.u]!=undefined || (msg.providerUID != undefined && friendsBySNUID[msg.providerUID]!=undefined));
		var showInPrivate = user!=null && (msg.u == user.UID || fromFriend);
		var showInPublic = msg.p && !showOnlyInPrivate;
			
		if (showInPublic && showPublicChat)
			addMsgToDiv(msg,publicDiv);
		

		if (showInPrivate && !showingNotificationUI)
		{
			var added = addMsgToDiv(msg,privateDiv);
			if (added && msg.u != user.UID && currentMsgDiv!=privateDiv)
				blink('lblPrivate',false,10);
			
			privateMsgCount++;		
		}
	} catch (e)
	{
		trace("renderMsg","ERROR: "+e.message);
	}
	
}


function normalizeUsername(un)
{
    return (un!=undefined) ? un.replace("'","\\'") : un;
}

function blink(elmName, on, times)
{
	times--;
	var style = $(elmName).style; 
	
	if (on || times==0)
		style.visibility='visible';
	else
		style.visibility='hidden';
	
	if (times!=0)
		setTimeout("blink('"+elmName+"',"+!on+","+times+")",150);	
}


function addMsgToDiv(msg, container)
{
   
	// skip doubles (we put msg.m in hidden textarea with above id)
	msg.id = container.id + '_'+msg.t+"_"+msg.u;
	if ($(msg.id)!=null && $(msg.id).innerHTML == msg.escapedMsg)
	{
		//trace("addMsgToDiv","Skipping "+Object.toJSON(msg));
		return false;
	}

	var div = new Element('div');
	div.innerHTML = publicMsgTemplate.evaluate(msg);
	if (container.childElements().length==MAX_DISPLAY_LENGTH)
	{	
		container.childElements()[MAX_DISPLAY_LENGTH-1].remove();
	}
	container.insert({top:div});
	return true;
}

function sendMsg()
{
	if (!loggedInToMsgServer) 
	{
		$('txtMsg').value="";
		return false;
	}
	var text = $('txtMsg').value.replace(/(<([^>]+)>)/ig,"");
	text = text.replace(/\\/g, "");
	text = text.strip();
	
	if(text=="" || text==textboxWatermark) return false;
	var isPublic = $('chkPublic').checked;
	

	trace('sendMsg',"Sending msg. public="+isPublic);
	$('btnUpdate').disabled = true;
	$('txtMsg').disabled=true;
	

	///send message.
	new Ajax.Request('API.ashx?f=s',  {
		method:'post', 
		parameters: {e:eventID, p:isPublic, m:text},
		onSuccess:sendMsg_CB,
		onFailure: function(res){ ajaxFail('sendMsg',res); $('btnUpdate').disabled = false; $('txtMsg').disabled=false; }
	});
	return false;	
}

function sendMsg_CB(res)
{
	$('btnUpdate').disabled = false;
	$('txtMsg').disabled=false;
	$('txtMsg').value="";
	$('txtMsg').focus();
	
	trace("sendMsg_CB",res.responseText);
	
	if (res.responseText=="0") return;
	if (res.responseText=="2") 
	{
		// not logged in
		return;
	}
	
	eval("msg = "+res.responseText);
	renderMsg(msg,false);

	///set status.
	var isSetStatus = $('chkSetStatus').checked;
	if(isSetStatus)
	{
//	if (setStatusOnMsg) {
	    var statusMsg = msg.m;
	    var curSuffix = null;
	    if(updateSuffix != undefined && updateSuffix.length>0)
	        curSuffix = " " + updateSuffix;
	        
	    setStatus(statusMsg, curSuffix);
	}

	// report event
	report('sendMsg_' + msg.n);
}


function showLoginUI()
{
	trace("showLoginUI",null);
	$('divLogin').show();
	var params=
	{
		containerID:"divLoginButtons",
		height:80,
		width:230,
		showTermsLink:false,
		hideGigyaLink: true,
		UIConfig:loginUIConfig,
		onError:function() {retry("showLoginUI()");}
	}
	
	gigya.services.socialize.showLoginUI(conf,params);
	$('divLoggedIn').hide();
}

function ajaxFail(where, transport)
{
	trace(where,transport.status +": "+transport.statusText);
}
	
function trace(source,msg)
{
	if (!traceEnabled) return;
	if (msg==null) msg = "";
	var isError = msg.indexOf("ERROR:")!=-1;
	var div = new Element("div");
	if (isError)
		div.style.color = "red";
	div.update("<b>"+source + ":</b><br>"+msg+"<br><hr>");
	traceDiv.insert({top:div});
	/*
	if (isError) 
	{
		alert(source+">"+msg);
	}*/
}

function logout()
{
    report("logout");
	setTimeout("logoutFromMsgSrv()",100);
	gigya.services.socialize.logout(conf);
	gigya.services.socialize.disconnect(conf);
	$('tabPrivate').hide();
	$('tabConnect').hide();
	privateDiv.update("");
	showTab('public');
	user = null;
	friends = null;
	friendsByUID = null;
	friendsBySNUID = null;
	friendIDs = new Array();
	friendSigs = new Array();
	friendIDsStr = null;
	friendSigsStr = null;
	recentMsgs = null;
	friendsMsgs = null;
	UIDSig = null;
	UIDStamp = null;
	connectedAtStartup = false;
	privateMsgCount = 0;	
	loggedInToMsgServer = false;
}

function showTab(tabName)
{
	var tab;
	var div;

	switch(tabName)
	{
		case 'public':
			tab = $('tabPublic');
			div = publicDiv;
			break;
		case 'private':
			tab = $('tabPrivate');
			div = privateDiv;
			//privMsgIndicator(false);
			break;
		case 'trace':
			tab = $('tabTrace');
			div = traceDiv;
			break;
			
	}
	if(tab==undefined)return;
	
	tab.className="selected";
	tab.siblings().each(
		function(elm) { elm.removeClassName("selected"); }
	);
	
	if (currentMsgDiv!=null)
		currentMsgDiv.hide();
	else{
        publicDiv.hide();
        privateDiv.hide();
        traceDiv.hide();		
	}
	div.show();
	adjustDivHeight(div);
	currentMsgDiv = div;
	
	//if (tabName=='private' && (!showingNotificationUI && !isIE()))
	if (tabName=='private' && ((!notificationShown && privateMsgCount==0 && !isIE())) ) 
	{
		// hiding and showing the div requires reinit in FF
		showNotificationUI();
	} 
}

function reply(userName)
{
	if (user==null) return; //can't reply if not loggedin
	WatermarkFocus($('txtMsg'));
	$('txtMsg').value = "@"+userName+" ";
}

function adjustDivHeight(div)
{
	if (div==null || div==undefined) return;
	var padding = 16;
	if (isIE())
		padding=12;
    var newHeight = (self.innerHeight || (document.documentElement.clientHeight || document.body.clientHeight)) - div.cumulativeOffset().top - padding;
	if (newHeight<=0) return;
	div.style.height =  newHeight + "px";
}

function showProfile(url)
{
	window.open(url,"_msgSrvProfile");
}

function isIE()
{
	return /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
}

function doResize()
{
	adjustDivHeight(publicDiv);
	adjustDivHeight(privateDiv);
	adjustDivHeight(traceDiv);
}

function renderTwitterNames(text,templateHTML)	
{
	return text.replace(/(^|[ ])[@][A-Za-z0-9-_]+/g, function(u) 
	{
		var username = u.replace("@","");
		var tmp = new Template(templateHTML);
		return tmp.evaluate({'username':username});
	});
};

function getTweets()
{
	if (twitterHashtag=="") return;
	
	if (twitterRefreshParams==null)
		twitterRefreshParams = "?rpp=50&q="+escape(twitterHashtag)+"&callback=getTweets_CB";
	var url = twitterBaseURL  + twitterRefreshParams;
	trace("getTweets",url);
	var elm = document.createElement("script");
	elm.src= url;
	document.body.appendChild(elm);
}

function getTweets_CB(res)
{
	twitterRefreshParams = res.refresh_url+"&callback=getTweets_CB";
	trace("getTweets_CB",Object.toJSON(res));
	//var end = Math.min(res.results.length,3);
	var tweets;
	if (twitterMaxFill!=-1)
		tweets = res.results.slice(0,twitterMaxFill);
	else
		tweets = res.results;
	tweets.reverse().each(
		function(t)
		{
			
			var msg = {};
			msg.t = new Date(t.created_at).getTime();
			// show only tweets that are newer than our recent MsgServer msg
			if (msg.t<lastMsgTime) 
			{
				//trace("getTweets_CB","tweet "+new Date(msg.t)+" is older than first msgServer msg "+new Date(msgServerMostRecentTime));
				return;
			}
			
			msg.m = t.text;
			msg.n = "twitter";
			msg.un = t.from_user;
			msg.p = true;
			msg.pu = "http://twitter.com"+t.from_user;
			msg.up = t.profile_image_url;
			msg.providerUID = t.from_user_id;			
			
			
			renderMsg(msg,false);
		}
	);

}

function WatermarkFocus(txtElem) 
{
	if (txtElem.value != textboxWatermark)  return;
	txtElem.value = '';
	txtElem.style.color="black";
}

function WatermarkBlur(txtElem) 
{
	if (txtElem.value != '') return;
	txtElem.value = textboxWatermark;
	txtElem.style.color="silver";
}

function retry(funcName)
{
	var timeout = Math.floor((RETRY_MAX-RETRY_MIN-1)*Math.random()) + RETRY_MIN;
	setTimeout(funcName, timeout);
}

Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--) {
        if (this[i] === obj) {
            return true;
        }
    }
    return false;
}

var progress = {
    getElm: function(){
        return $('progress');
    },
    
    show: function(){
        this.getElm().show();
        this.setStyle();
    },
    
    setStyle: function(){
       
        this.getElm().setStyle({
            zIndex:99999,
            position:"absolute",
            top: this.getTop() + "px",
            left: this.getLeft() + "px"
        });
    },
    
    getTop: function(){
        return ((document.viewport.getDimensions().height - this.getElm().getHeight())/2);
    },
     getLeft: function(){
        return ((document.viewport.getDimensions().width - this.getElm().getWidth())/2)
    },  
    
    hide: function(){
        this.getElm().hide();
    }
}

/*
function handleErrors(errStr, url, lineNum)
{ 
	if (traceEnabled)
	{
		alert("ERROR: "+errStr);
		debugger;
	}
}*/

window.onresize = doResize; 

if (!traceEnabled)
	window.onerror=null;

