﻿// JScript File

var ratecount = 0;
function ratehome(nr, nota)
{
  ptorate = ptorate + 1;
  if (ptorate > 33 )
     ptorate = 1;
  document.getElementById("ptorateimg").src = "homerating/"+ptorate+".jpg";
  ratecount ++;
  if (ratecount > 33)
  {
    if (inFacebook)
        location = "editprofile.aspx";
    else
        location = "register.aspx";
  }
}

function startMovingPics()
{
    if (movingStopped)
    {
        movingStopped = false;
        timer = setTimeout("movePics()",200);
    }
}
var timer;
function movePics()
{
    if (movingStopped) return;
    mpicleft -= 3;
    if (mpicleft < -2200)
        mpicleft = 700;
    var mpics = document.getElementById("movingpics");
    mpics.style.left = mpicleft+"px";
    timer = setTimeout("movePics()",100);
}

function stopMovingPics()
{
    movingStopped = true;
    clearTimeout(timer);
}

function ShowBalloonNoTimeout()
{
     
     var balloon = document.getElementById("balloon");
     if (balloon != null)
     {
        balloon.style.visibility = "visible";
     }
     var yellowballoon = document.getElementById("yellowballoon");
     if (yellowballoon != null)
     {
        yellowballoon.style.visibility = "visible";     
     }   
}

function HideYellowBalloon()
{
     var yellowballoon = document.getElementById("yellowballoon");
     if (yellowballoon != null)
     {
        yellowballoon.style.visibility = "hidden";
     }
}

function boxfocus(ctrl, graytext)
{
    if (ctrl.value==graytext) ctrl.value='';
    ctrl.style.color="#000";
}

function boxblur(ctrl, graytext)
{
    if (ctrl.value=='')
    {
        ctrl.value = graytext;
        ctrl.style.color="#aaa";
    }
}

function bboxfocus(ctrl, graytext)
{
    if (ctrl.value==graytext) ctrl.value='';
    ctrl.style.color="#3b5998";
}

function bboxblur(ctrl, graytext)
{
    if (ctrl.value=='')
    {
        ctrl.value = graytext;
        ctrl.style.color="#aaa";
    }
}

function txtfocus(ctrl)
{
    if (ctrl.value=='Paste HTML, Embed or Flash' || ctrl.value=='What are you doing?' || ctrl.value=='post a comment here...') ctrl.value='';
    ctrl.style.color="#000";
}

function txtblur1(ctrl)
{
    if (ctrl.value=='')
    {
        ctrl.value = 'Paste HTML, Embed or Flash';
        ctrl.style.color="#aaa";
    }
}

function txtblur2(ctrl)
{
    if (ctrl.value=='')
    {
        ctrl.value = 'What are you doing?';
        ctrl.style.color="#aaa";
    }
}

function txtblur3(ctrl)
{
    if (ctrl.value=='')
    {
        ctrl.value = 'post a comment here...';
        ctrl.style.color="#aaa";
    }
}

function preparerate(itemid, nota)
{
   for(var i=1;i<=5;i++)
   {
      if (i<=nota)
        document.getElementById("rateimg"+itemid+i).src="images/lollipopactive.png";
      else
        document.getElementById("rateimg"+itemid+i).src="images/lollipopinactive.png";
   } 
   var ratelabel = document.getElementById("ratelabel"+itemid);
   ratelabel.innerHTML = "&nbsp;rate this "+nota;   
}

function unpreparerate(itemid)
{   
   var oscore = 0;
   var oscoreelem = document.getElementById("oscore"+itemid);
   if (oscoreelem != null)
   {
        oscore = Number(oscoreelem.value);
   }
   for(var i=1;i<=5;i++)
   {
        var starname = "lollipopinactive";        
        if (oscore > i-1 && oscore < i)
        {
            starname = "lollipophalf";
        }
        else if (oscore >= i)
        {
            starname = "lollipopactive";
        }

        document.getElementById("rateimg"+itemid+i).src="images/"+starname+".png";
   }
   var votenr = document.getElementById("votenr"+itemid);
   var ratelabel = document.getElementById("ratelabel"+itemid);
   ratelabel.innerHTML = "&nbsp;"+votenr.value+"&nbsp;votes";
   
}

function rateitem(itemid, category, ownerid, nota)
{
   var ratelabel = document.getElementById("ratelabel"+itemid);
   ratelabel.innerHTML = "rating...";
   var params = "uniqueid="+itemid+"&category="+category+"&ownerid="+ownerid+"&userid=" + userid + "&rate=" + nota;
  
   makePOSTRequest("rateitem.ashx", params, RateItemDone);                                
}

function ratetopitemEx(itemid, category, ownerid, nota)
{
   var params = "uniqueid="+itemid+"&category="+category+"&ownerid="+ownerid+"&userid=" + userid;
   window.open("allscores.aspx?"+params,"mywindow","menubar=1,resizable=1,width=650,height=550");                                
}

function ratetopitem(itemid, category, ownerid, nota)
{
   var ratelabel = document.getElementById("ratelabel"+itemid);
   ratelabel.innerHTML = "rating...";
   var params = "uniqueid="+itemid+"&category="+category+"&ownerid="+ownerid+"&userid=" + userid + "&rate=" + nota;
  
   makePOSTRequest("ratetopitem.ashx", params, RateItemDone);                                
}

function RateItemDone(result)
{
    try {
        var resultObj = eval('(' + result + ')');
        var ratelabel = document.getElementById("ratelabel"+resultObj.itemid);    
        if (ratelabel != null)
        {
            ratelabel.innerHTML = "&nbsp;thank you";
            ratelabel.title = "you rated "+resultObj.rate;
            document.getElementById("votenr"+resultObj.itemid).value = resultObj.votes;
            setTimeout("DisplayRate('"+resultObj.itemid+"','&nbsp;you rated "+resultObj.rate+"')", 2000);
            setTimeout("DisplayRate('"+resultObj.itemid+"','&nbsp;"+resultObj.votes+" votes')", 4000);        
        }
        
        var oscoreelem = document.getElementById("oscore"+resultObj.itemid);
        if (oscoreelem != null)
        {
            oscoreelem.value = resultObj.oscore;
            unpreparerate(resultObj.itemid);
        }  
    } catch (err) 
    {
        alert(err.description);
        alert(result);
    }  
}

function rateperson(personid, rate)
{
   var params = "uniqueid=hotness"+personid+"&category=hotness&ownerid="+personid+"&userid=" + userid + "&rate="+rate;  
   makePOSTRequest("rateitem.ashx", params, RatePersonDone); 
   document.getElementById("votepanel").style.visibility="hidden";
   document.getElementById("votestatistics").style.visibility="visible"; 
   document.getElementById("votestatus").innerHTML = ""; 
}

function ratetopperson(personid, rate)
{
   var params = "uniqueid=hotness"+personid+"&category=hotness&ownerid="+personid+"&userid=" + userid + "&rate="+rate;  
   makePOSTRequest("ratetopitem.ashx", params, RatePersonDone);                             
}

function VoteAgain()
{
   document.getElementById("votepanel").style.visibility="visible";
   document.getElementById("votestatistics").style.visibility="hidden";
}

function RatePersonDone(result)
{
    try {
        var resObj = eval('(' + result + ')');      
        document.getElementById("votestatus").innerHTML = "<a title=\"change rating\" href=\"javascript:VoteAgain()\">R</a>"; 
        document.getElementById("hotcount").innerHTML = resObj.votes3;    
        document.getElementById("cutecount").innerHTML = resObj.votes2;
        document.getElementById("okaycount").innerHTML = resObj.votes1;
//        if (resObj.rate==1) 
//            document.getElementById("myvote").innerHTML = "you rated Okay";
//        if (resObj.rate==2) 
//            document.getElementById("myvote").innerHTML = "you rated Cute";  
//        if (resObj.rate==3) 
//            document.getElementById("myvote").innerHTML = "you rated Hot";                         
    } catch (err) 
    {
        alert(err.description);
        alert(result);
    }  
}

function DisplayRate(itemid, labelstr)
{
    var ratelabel = document.getElementById("ratelabel"+itemid);
    if (ratelabel != null)
    {
        ratelabel.innerHTML = labelstr;
    }
}

function starrate(personid, rate)
{

}
var shmingleVisible = false;

function HideShmingle()
{
     var mbutton = document.getElementById("shmingle");
     if (mbutton != null)
     {
	            mbutton.style.display = "none";
                shmingleVisible = false;
     }
}

function ShowList(listname, listtitle)
{
    var innershmingle = document.getElementById("innershmingle");
    innershmingle.innerHTML = "Loading...";
    
    document.getElementById("menutabBebikiFriends").className = "menutab";
    document.getElementById("menutabfollowsme").className = "menutab";
    document.getElementById("menutabifollow").className = "menutab";
    document.getElementById("menutabifaved").className = "menutab";
    document.getElementById("menutabfavedme").className = "menutab";
    document.getElementById("menutabifaned").className = "menutab";
    document.getElementById("menutabfanedme").className = "menutab";
    document.getElementById("menutabiprivateaccess").className = "menutab";
    document.getElementById("menutabprivateaccessedme").className = "menutab";
    document.getElementById("menutabiblocked").className = "menutab";

    document.getElementById("menutab"+listname).className = "menutabS";
    
    var addremovediv = document.getElementById("addremovediv");
    if (listname == "bebikifriends")
    {
        addremovediv.innerHTML = "<a href=\"friends.aspx\">Add/Remove "+listtitle+"</a>";
    }
    else if (listname.substring(0,1)=="i")
    {
        addremovediv.innerHTML = "<a href=\"editlist.aspx?list="+listname+"\">Add/Remove "+listtitle+"</a>";
    }
    else
    {
        addremovediv.innerHTML = "";
    }
    var marafets = "userid=" + userid + "&list="+listname;    
    makePOSTRequest("editlistget.ashx?"+marafets, "", ShowListDone);
    
}

function ShowListDone(response)
{
    var innershmingle = document.getElementById("innershmingle");
    innershmingle.innerHTML = response;  
}

function ShowFans()
{
    document.getElementById("followersfans").innerHTML = "Loading...";
    
    document.getElementById("followerstab").className = "menutab";
    document.getElementById("fanstab").className = "menutabS";
    
    var marafets = "userid=" + ownerid + "&list=fanedme";   
    makePOSTRequest("getfollowersfans.ashx?"+marafets, "", ShowFansDone);    
}

function ShowFansDone(response)
{
    var followersfans = document.getElementById("followersfans");
    followersfans.innerHTML = response;  
}

function ShowFollowers()
{
    document.getElementById("followersfans").innerHTML = "Loading...";
    
    document.getElementById("followerstab").className = "menutabS";
    document.getElementById("fanstab").className = "menutab";
    
    var marafets = "userid=" + ownerid + "&list=followsme";   
    makePOSTRequest("getfollowersfans.ashx?"+marafets, "", ShowFansDone);    
}

function ShowFansDone(response)
{
    var followersfans = document.getElementById("followersfans");
    followersfans.innerHTML = response;  
}

function ShowSh2(listname)
{
    var shmingle2 = document.getElementById("shmingle2");
    shmingle2.innerHTML = "Loading...";
    
    document.getElementById("shmingle2bebikifriends").className = "menutab";
    document.getElementById("shmingle2followsme").className = "menutab";
    document.getElementById("shmingle2fanedme").className = "menutab";
    
    document.getElementById("shmingle2"+listname).className = "menutabS";
    
    var marafets = "userid=" + userid + "&ownerid=" + ownerid + "&list="+listname;  
    
    if(document.getElementById("addremovelink") != null)
    {
        if (listname == "ifaved")
        {
            document.getElementById("addremovelink").innerHTML = "<a href=\"editlist.aspx?list=ifaved&id=" + ownerid + "\">Add/Remove Favorites</a>";
        }
        else if (listname == "bebikifriends")
        {
            document.getElementById("addremovelink").innerHTML = "<a href=\"friends.aspx?id=" + ownerid + "\">Add/Remove Friends</a>";
        }
        else
        {
            document.getElementById("addremovelink").innerHTML = "";
        }
    }      
    makePOSTRequest("editlistget2.ashx?"+marafets, "", ShowSh2Done);    
}

function ShowSh2Done(response)
{
    var shmingle2 = document.getElementById("shmingle2");
    shmingle2.innerHTML = response;  
}

var shmingle2ShowsMore = false;
function ToggleShowMore()
{
    var shmingle2 = document.getElementById("shmingle2");   
    var showMoreSh2 = document.getElementById("showMoreSh2");
    if (shmingle2ShowsMore)
    {
        showMoreSh2.src = "images/showmore.gif";
        showMoreSh2.title = "Expand";
        showMoreSh2.onmouseover = new Function("this.src='images/showmorehi.gif'");
        showMoreSh2.onmouseout = new Function("this.src='images/showmore.gif'");
        shmingle2.style.height = "100px"; 
        shmingle2ShowsMore = false;       
    }
    else
    {
        showMoreSh2.src = "images/showless.gif";
        showMoreSh2.title = "Minimize";
        showMoreSh2.onmouseover = new Function("this.src='images/showlesshi.gif'");
        showMoreSh2.onmouseout = new Function("this.src='images/showless.gif'");        
        shmingle2.style.height = "280px";
        shmingle2ShowsMore = true;
    }
}

var followersfansShowsMore = false;
function ToggleFollowersFans()
{
    var followersfans = document.getElementById("followersfans");   
    var showMoreFollowersButton = document.getElementById("showMoreFollowersFans");
    if (followersfansShowsMore)
    {
        showMoreFollowersButton.src = "images/showmore.gif";
        showMoreFollowersButton.title = "Expand";
        showMoreFollowersButton.onmouseover = new Function("this.src='images/showmorehi.gif'");
        showMoreFollowersButton.onmouseout = new Function("this.src='images/showmore.gif'");
        followersfans.style.height = "60px"; 
        followersfansShowsMore = false;       
    }
    else
    {
        showMoreFollowersButton.src = "images/showless.gif";
        showMoreFollowersButton.title = "Minimize";
        showMoreFollowersButton.onmouseover = new Function("this.src='images/showlesshi.gif'");
        showMoreFollowersButton.onmouseout = new Function("this.src='images/showless.gif'");        
        followersfans.style.height = "280px";
        followersfansShowsMore = true;
    }
}


function ToggleMingleButton()
{
    if (shmingleVisible)
    {
         mbutton = document.getElementById("shmingle");
         if (mbutton != null)
         {
	            mbutton.style.display = "none";
                shmingleVisible = false;
         }
    }
    else
    {
         mbutton = document.getElementById("shmingle");
         if (mbutton != null)
         {
            mbutton.style.display = "block";   
            shmingleVisible = true;
		    mbutton.style.height = "260px";
            mbutton.style.width = "728px";
         }
         var balloon = document.getElementById("balloon");
         if (balloon) balloon.style.visibility = "hidden";
    }
}

//function ToggleMingleButton()
//{
//    if (shmingleVisible)
//    {
//         mbutton = document.getElementById("shmingle");
//         if (mbutton != null)
//         {
//            DecrementShmingle();
//         }
//    }
//    else
//    {
//         mbutton = document.getElementById("shmingle");
//         if (mbutton != null)
//         {
//            mbutton.style.display = "block";   
//            shmingleVisible = true;
//            mbuttonheight = 0;
//            mbuttonwidth = 6;
//            IncrementShmingle();
//         }
//         var balloon = document.getElementById("balloon");
//         if (balloon) balloon.style.visibility = "hidden";
//    }
//}


var mbutton;
var mbuttonheight;
var mbuttonwidth;
function IncrementShmingle()
{
    mbuttonheight += 28;
    mbuttonwidth += 71;
	mbutton.style.height = mbuttonheight+"px";
    mbutton.style.width = mbuttonwidth+"px";
    
	if (mbuttonwidth < 710)
	{
	    setTimeout('IncrementShmingle()', 50);
	}
	else
	{
		mbutton.style.height = "280px";
        mbutton.style.width = "728px";
	}
}

function DecrementShmingle()
{
    mbuttonheight -= 28;
    mbuttonwidth -= 71;
	mbutton.style.height = mbuttonheight+"px";
    mbutton.style.width = mbuttonwidth+"px";
    
	if (mbuttonwidth > 71)
	{
	    setTimeout('DecrementShmingle()', 50);
	}
	else
	{
	    mbutton.style.display = "none";
        shmingleVisible = false;
    }	
}

function PostNewDiscussion()
{
    setEditorHtml();
    document.getElementById("uniqueid").value = getRandomID();
    document.getElementById("newdiscussion").value = document.getElementById("editorhtml").value;
    document.postform.submit();
}

function SaveNewPostMessage()
{
    setEditorHtml();
    document.getElementById("newpostmessage").value = document.getElementById("editorhtml").value;
    document.saveform.submit();
}

function AddNewHtmlMessage(sendThreadId, middlecolwidth)
{
    if (postAsId == "")
    {
        postAsId = userid;
        postAsName = userFirstName;
        postAsPicUrl = userPicUrl;
    }
    setEditorHtml();
    AddNewMessageEx(sendThreadId, document.getElementById("editorhtml").value, false, middlecolwidth);
    
    messageboardvisible = true;
    ToggleNewMessage();
}

function AddNewMessage(sendThreadId, middlecolwidth)
{
    if (postAsId == "")
    {
        postAsId = userid;
        postAsName = userFirstName;
        postAsPicUrl = userPicUrl;
    }
    var newReply = document.getElementById('newreply');
    if (newReply.value=='What are you doing?' || newReply.value=='post a comment here...' || newReply.value == "") return;
    AddNewMessageEx(sendThreadId, newReply.value, true, middlecolwidth);
    newReply.value ='post a comment here...';
    newReply.style.color = "#aaa";    
}    
    
function AddNewMessageEx(sendThreadId, msgVal, hescape, middlecolwidth)
{
    var escapedMessage = escape(msgVal);
    var uniqueid = getRandomID();
    ServerAddReply(uniqueid, ownerid, postAsId, escapedMessage, sendThreadId);
    var currentTime = new Date()
    var month = currentTime.getMonth() + 1;
    var day = currentTime.getDate();
    var year = currentTime.getFullYear();
    var hours = currentTime.getHours();
    var minutes = currentTime.getMinutes();
    var rDate = month+"/"+day+"/"+year+" "+hours+":"+minutes;
    InsertMessageAtTop(uniqueid, postAsId, postAsName, postAsPicUrl, escapedMessage, ownerFirstName, rDate, hescape, middlecolwidth);
}
 
 function InsertMessageAtTop(uniqueid, mUserId, mUserFirstName, mPicUrl, mMessage, mProfileName, mDate, hescape, middlecolwidth)
 {   
    var rFrom = "<span class='replylink'><a href='profile.aspx?id=" + mUserId + "'>" + mUserFirstName + "</a></span>";
    var rImage = "<a href='profile.aspx?id=" + mUserId + "'><img src='" + mPicUrl + "' border='0'/></a>";
    var mheader = "<table id=\"replyinfo" + uniqueid + "\" cellspacing=\"0\" cellpadding=\"0\" width=\"100%\" style=\"visibility:hidden;font-size:xx-small;color:#aaa;\"><tr><td>@ " + userFirstName + "</td><td align=\"right\">" + mDate + "</td></tr></table>";


    var encodedMessage = mheader
    if (hescape)
        encodedMessage += HtmlEncode(unescape(mMessage));
    else
        encodedMessage += unescape(mMessage);
           
    
    var cellclass1 = "bebiki_cell1";
    var cellclass2 = "bebiki_cell2";
    var cellclass;

    var result = "";
    if (rowindex % 2 == 0)
        cellclass = cellclass2;
    else
        cellclass = cellclass1;
    
    var messagetable = document.getElementById("messagetable");
    var newRow = messagetable.insertRow(0);
    newRow.id = "mrow"+uniqueid;
    newRow.onmouseover= new Function("ShowElement('replyinfo" + uniqueid + "')");
    newRow.onmouseout= new Function("HideElement('replyinfo" + uniqueid + "')");    
    var leftCell = newRow.insertCell(0);
    var rightCell = newRow.insertCell(1);
    
    leftCell.className = cellclass;
    leftCell.style.padding="3px";
    leftCell.vAlign = "top";    
    leftCell.setAttribute("width","72");
    leftCell.style.borderBottom = "solid 1px #aaa";
    newAddedLeftCell = leftCell;
    
    rightCell.className = cellclass;
    rightCell.style.padding="3px";
    rightCell.vAlign = "top";
    rightCell.style.borderBottom = "solid 1px #aaa";
    rightCell.setAttribute("width",middlecolwidth);
    rightCell.setAttribute("align","left");
        
    var closeCell = newRow.insertCell(2);
    closeCell.className = cellclass;
    closeCell.style.padding="1px";
    closeCell.vAlign = "top";    
    closeCell.setAttribute("width","10");
    closeCell.style.borderBottom = "solid 1px #aaa";
    closeCell.innerHTML = "<div style=\"cursor:pointer;\" onclick=\"DeleteReply('" + uniqueid + "', '" + userid + "')\"><img border=\"0\" title=\"Delete\" src=\"images/deletemessage.gif\" onmouseover=\"this.src='images/deletemessagehi.gif'\" onmouseout=\"this.src='http://Bebiki.com/images/deletemessage.gif'\"/></div>";

    newAddedPic = rImage + "<br>" + rFrom;
    newAddedMessage = encodedMessage;
    newAddedCell = rightCell;
    newAddedRow = newRow;
    newRow.style.height = "10px";
    newAddedHeight = 0;
    IncrementHeight();
    rowindex++;
}

var newAddedPic = "";
var newAddedMessage = "";
var newAddedRow;
var newAddedLeftCell;
var newAddedCell;
var newAddedHeight = 0;

function IncrementHeight()
{
    if (newAddedHeight < 65)
    {
        newAddedRow.style.height = newAddedHeight+"px";
        newAddedHeight +=20;
        setTimeout("IncrementHeight()",100);
    }
    else
    {
        newAddedLeftCell.innerHTML = newAddedPic;
        newAddedCell.innerHTML = newAddedMessage;
    }
}

function ServerAddReply(uniqueid, ownerid, userid, newreply, sendThreadId)
{
    var parames = "uniqueid="+uniqueid+"&ownerid=" + ownerid + "&userid=" + userid + "&messagebroadcast=" + messagebroadcast + "&newreply=" + newreply;
    if (sendThreadId)
    {
        parames = "threadid="+threadId+"&"+parames;
    }
    makePOSTRequest("addreply.ashx", parames, AddReplyDone);
}

function AddReplyDone(response)
{
   if (response == "OK")
   {
       //  
   }
   else
   {
       alert(response);
   }   
}

function DeleteReply(uniqueid, replyuserid, threadid)
{
    if (confirm("Are you sure you want to delete this post?"))
    {
        var params = "uniqueid="+uniqueid+"&ownerid=" + ownerid + "&replyuserid=" + replyuserid+"&threadid="+threadid;
        makePOSTRequest("removereply.ashx", params, AddReplyDone);
        decrementingRow = document.getElementById("mrow"+uniqueid);
        decrementingRow.cells[0].innerHTML = "";
        decrementingRow.cells[1].innerHTML = "";
        decrementingRow.cells[2].innerHTML = "";
        decrementingHeight = 60;
        DecrementHeight();
    }
}

function DeleteThread(threadid)
{
    if (confirm("Are you sure you want to delete thread "+threadid+" ?"))
    {
        var params = "userid=" + userid+"&threadid="+threadid;
        makePOSTRequest("removethread.ashx", params, DeleteThreadDone);
    }
}

function DeleteThreadDone(response)
{
   if (response == "OK")
   {
       location = "threads.aspx";
   }
   else
   {
       alert(response);
   }   
}

function RemoveAppFromPlan(username, appid, subscriptionid)
{
    if (confirm("Are you sure you want to remove " + appid + " from your plan?"))
    {
        var params = "username=" + username+"&appid="+appid+"&subscriptionid="+subscriptionid;
        makePOSTRequest("removeappfromplan.ashx", params, RemoveAppFromPlanDone);
    }
}

function RemoveAppFromPlanDone(response)
{
   if (response.substring(0, 5) == "OK ~ ")
   {
       location = "subscription.aspx?id="+response.substring(5, response.length);
   }
   else
   {
       alert(response);
   }   
}

var decrementingRow;
var decrementingHeight;

function DecrementHeight()
{
    if (decrementingHeight > 0)
    {
        decrementingRow.style.height = decrementingHeight+"px";
        decrementingHeight -=10;
        setTimeout("DecrementHeight()",100);
    }
    else
    {
        var messagetable = document.getElementById("messagetable");
        for(var i=0; i<messagetable.rows.length; i++)
        {
            if (messagetable.rows[i].id == decrementingRow.id)
            {                 
                 messagetable.deleteRow[i];
            }
        }
    }
}

function HtmlEncode( value )
{
    var encoded = new String(value);
    
    encoded = encoded.replace(/&/g, "&amp;");
    encoded = encoded.replace(/</g, "&lt;");
    encoded = encoded.replace(/>/g, "&gt;");
    encoded = encoded.replace(/"/g, "&quot;");
    
    return encoded;
}

function ShowElement(elemid)
{
    var elem = document.getElementById(elemid);
    if (elem)
        elem.style.visibility='visible';
}

function HideElement(elemid)
{
    var elem = document.getElementById(elemid);
    if (elem)
        elem.style.visibility='hidden';
}

function GetLatestMessages()
{
    var params = "ownerid=" + ownerid + "&userid=" + userid + "&rafterid=" + rafterid + "&wafterid="+wafterid;
    makePOSTRequest("getrepliesafter.ashx", params, GetLatestMessagesDone);
    
    setTimeout("GetLatestMessages()", 15000);
}

var latestPosts = null;

function GetLatestMessagesDone(result)
{
    //alert(result);
    latestPosts = eval('(' + result + ')');
    if (latestPosts.rjson.length > 0)
    {
        for(var i=0;i<latestPosts.rjson.length;i++)
        {
           if (i == 0)
           {
                rafterid = latestPosts.rjson[0].replyid;
           }
           setTimeout("ScheduleMessageInsert("+i+")", 2000*(i+1));
        }
    }
    if (latestPosts.wjson.length > 0)
    {
        for(var i=0;i<latestPosts.wjson.length;i++)
        {
           if (i == 0)
           {
                wafterid = latestPosts.wjson[0].orderid;
           }
           setTimeout("ScheduleWidgetInsert("+i+")", 2000*(i+1));           
        }
    }    
}
 
function ScheduleMessageInsert(mIndex)
{
    if (latestPosts.rjson == null)
    {
       return;
    }
    var mObj = latestPosts.rjson[mIndex];
    
    var rRowElem = document.getElementById("mrow"+mObj.uniqueid);
    if (rRowElem == null)
    {
        InsertMessageAtTop(mObj.uniqueid, mObj.userid, mObj.username, mObj.picurl, mObj.message, mObj.rprofilename, mObj.rdate, true, "290");        
    }
    
    if (mIndex == (latestPosts.rjson.length -1))
    {
       latestPosts.rjson = null; 
    }
}

function ScheduleWidgetInsert(wIndex)
{
    //postedbyid
    //postedbyname
    //orderid
    //uniqueid
    //wdate
    if (latestPosts.wjson == null)
    {
       return;
    }
    var wObj = latestPosts.wjson[wIndex];
    var rRowElem = document.getElementById("widgetrow"+wObj.uniqueid);
    if (rRowElem == null)
    {
        InsertWidgetAtTop(wObj.uniqueid, ownerid, wObj.postedbyid, wObj.postedbyname, wObj.wdate);
    }
    if (wIndex == (latestPosts.wjson.length -1))
    {
       latestPosts.wjson = null; 
    }
}

function getRandomNumber(range)
{
	return Math.floor(Math.random() * range);
}

function getRandomChar()
{
	var chars = "abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ";
	return chars.substr( getRandomNumber(52), 1 );
}

function getRandomID()
{
	var str = "";
	for(var i = 0; i < 24; i++)
	{
		str += getRandomChar();
	}
	return str;
}

function getRandomShortID()
{
	var str = "";
	for(var i = 0; i < 12; i++)
	{
		str += getRandomChar();
	}
	return str;
}

function commentOnTopLolReply(uniqueid)
{
    var divelem = document.getElementById("commentdiv" + uniqueid);
    divelem.innerHTML = "<textarea id=\"commentarea"+uniqueid+"\" rows=\"2\" class=\"toplolcomment_area\"></textarea><br><input type=\"button\" class=\"roundbutton\" value=\"Reply\" onclick=\"AddNewTopLolComment('"+uniqueid+"')\"/>";
    document.getElementById("commentarea" + uniqueid).focus();
}

function AddNewTopLolComment(uniqueid)
{
    var divelem = document.getElementById("commentdiv" + uniqueid);
    var commentcontainer = document.getElementById("commentcontainer" + uniqueid);
    var originalMessage = document.getElementById("commentarea" + uniqueid).value;
    if (originalMessage == "")
    {
        divelem.innerHTML = "<span onclick=\"commentOnTopLolReply('" + uniqueid + "')\">- Add Comment</span>";
        return;
    }
    
    var commentText = HtmlEncode(originalMessage);
    for (var emIx = abrv.length - 1; emIx >= 0; emIx--)
    {
        var strtoreplace = "<img src='emoticons/" + (emIx + 1) + ".gif'>";
        var rwhat = abrv[emIx];
        do
        {
            commentText = commentText.replace(rwhat, strtoreplace);
        }
        while(commentText.indexOf(rwhat) > 0);
    }
    var rImage = "<a href='"+appCanvasUrl+"/profile.aspx?id=" + userid + "' target='_top'><img src='" + userPicUrl + "' style='vertical-align:middle' width='30' border='0'/></a>";
    commentcontainer.innerHTML += "<table class=\"toplolcomment_message\"><tr><td width=\"30\">"+rImage+"</td><td align=\"left\">"+commentText+"</td></tr></table>";
    divelem.innerHTML = "<span onclick=\"commentOnTopLolReply('" + uniqueid + "')\">- Add Comment</span>";
    
    var commentUniqueId = getRandomID();
    var params = "toploluniqueid="+uniqueid+"&ownerid=" + ownerid + "&userid=" + userid + "&uniqueid=" + commentUniqueId + "&newcomment=" + escape(originalMessage);
    makePOSTRequest("addcomment.ashx", params, AddReplyDone); 
}

function commentOnReply(uniqueid)
{
    var divelem = document.getElementById("commentdiv" + uniqueid);
    divelem.innerHTML = "<textarea id=\"commentarea"+uniqueid+"\" rows=\"2\" class=\"comment_area\"></textarea><br><input type=\"button\" class=\"roundbutton\" value=\"Post\" onclick=\"AddNewcomment('"+uniqueid+"')\"/>";
    document.getElementById("commentarea" + uniqueid).focus();
}

function widecommentOnReply(uniqueid)
{
    var divelem = document.getElementById("commentdiv" + uniqueid);
    divelem.innerHTML = "<textarea id=\"commentarea"+uniqueid+"\" rows=\"2\" class=\"widecomment_area\"></textarea><br><input type=\"button\" class=\"roundbutton\" value=\"Post\" onclick=\"AddNewwidecomment('"+uniqueid+"')\"/>";
    document.getElementById("commentarea" + uniqueid).focus();
}

function AddNewcomment(uniqueid)
{
    var divelem = document.getElementById("commentdiv" + uniqueid);
    var commentcontainer = document.getElementById("commentcontainer" + uniqueid);
    var originalMessage = document.getElementById("commentarea" + uniqueid).value;
    if (originalMessage == "")
    {
        divelem.innerHTML = "<span onclick=\"commentOnReply('" + uniqueid + "')\">- Comment</span>";
        return;
    }
    
    var commentText = HtmlEncode(originalMessage);
    for (var emIx = abrv.length - 1; emIx >= 0; emIx--)
    {
        var strtoreplace = "<img src='emoticons/" + (emIx + 1) + ".gif'>";
        var rwhat = abrv[emIx];
        do
        {
            commentText = commentText.replace(rwhat, strtoreplace);
        }
        while(commentText.indexOf(rwhat) > 0);
    }
    var rImage = "<a href='profile.aspx?id=" + userid + "' target='_parent'><img src='" + userPicUrl + "' style='vertical-align:middle' width='30' border='0'/></a>";
    commentcontainer.innerHTML += "<table class=\"comment_message\"><tr><td width=\"30\">"+rImage+"</td><td align=\"left\">"+commentText+"</td></tr></table>";
    divelem.innerHTML = "<span onclick=\"commentOnReply('" + uniqueid + "')\">- Comment</span>";
    
    var commentUniqueId = getRandomID();
    var roidid = document.getElementById("roid"+uniqueid).value;
    var params = "replyuniqueid="+uniqueid+"&ownerid=" + ownerid + "&userid=" + userid + "&uniqueid=" + commentUniqueId + "&roidid=" + roidid + "&newcomment=" + escape(originalMessage);
    makePOSTRequest("addcomment.ashx", params, AddReplyDone); 
}

function AddNewwidecomment(uniqueid)
{
    var divelem = document.getElementById("commentdiv" + uniqueid);
    var commentcontainer = document.getElementById("commentcontainer" + uniqueid);
    var originalMessage = document.getElementById("commentarea" + uniqueid).value;
    if (originalMessage == "")
    {
        divelem.innerHTML = "<span onclick=\"widecommentOnReply('" + uniqueid + "')\">- Comment</span>";
        return;
    }
    
    var commentText = HtmlEncode(originalMessage);
    for (var emIx = abrv.length - 1; emIx >= 0; emIx--)
    {
        var strtoreplace = "<img src='emoticons/" + (emIx + 1) + ".gif'>";
        var rwhat = abrv[emIx];
        do
        {
            commentText = commentText.replace(rwhat, strtoreplace);
        }
        while(commentText.indexOf(rwhat) > 0);
    }
    var rImage = "<a href='profile.aspx?id=" + userid + "' target='_parent'><img src='" + userPicUrl + "' style='vertical-align:middle' width='30' border='0'/></a>";
    commentcontainer.innerHTML += "<table class=\"widecomment_message\"><tr><td width=\"30\">"+rImage+"</td><td align=\"left\">"+commentText+"</td></tr></table>";
    divelem.innerHTML = "<span onclick=\"widecommentOnReply('" + uniqueid + "')\">- Comment</span>";
    
    var commentUniqueId = getRandomID();
    var roidid = document.getElementById("roid"+uniqueid).value;
    var params = "threadid="+threadId+"&replyuniqueid="+uniqueid+"&ownerid=" + ownerid + "&userid=" + userid + "&uniqueid=" + commentUniqueId + "&roidid=" + roidid + "&newcomment=" + escape(originalMessage);
    makePOSTRequest("addcomment.ashx", params, AddReplyDone);
}

//////////////smiley


var abrv =  [":)", ":(", ";)", ":D", ";;)", ":-/", ":x", ":=)", ":p", ":*", "=D", "#-o", ":}", "B-)", ":-s", ":((", ":))", "/:)", "O:)", "@};-", "8-}", "=;", "(:|", "::|"];


function lolbuilderbuttonH()
{
    document.getElementById("lolbuilderbutton").className = "lol_buttonH";
}

function lolbuilderbuttonD()
{
    document.getElementById("lolbuilderbutton").className = "lol_button";
}

function ShowEmoticons()
{
     var emoticons = document.getElementById("emoticons");
     emoticons.style.height="72px";
     
     emoticons.style.visibility='visible';
     emoticons.style.display='block';
}

function AddSmilic(smilic)
{
    var newReply = document.getElementById('newreply');
    if (newReply.value=='What are you doing?' || newReply.value=='post a comment here...') newReply.value='';
    newReply.style.color="#000";
    newReply.value += smilic + ' ';
    HideEmoticons(); 
    newReply.focus();
}

function AddSmilic2(smilic)
{
    var newReply = document.getElementById('msgbody');
    if (newReply.value=='type message here...') newReply.value='';
    newReply.style.color="#000";
    newReply.value += smilic + ' ';
    HideEmoticons(); 
    newReply.focus();
}

function HideEmoticons()
{
     var emoticons = document.getElementById("emoticons");
     emoticons.style.height="1px";
     
     emoticons.style.visibility='hidden';
     emoticons.style.display='none';
}
/////////////////smiley

/////minglewidget


function bebikiScheduleIframeResize(eid)
{
    var iframeElem = document.getElementById(eid);
    if (iframeElem != null)
    {
        try
        {
            var iDoc = document.getElementById(eid).contentWindow.document;
            if (iDoc != null)
            {
                var ifrH = iDoc.body.scrollHeight;
                if (ifrH < 8)
                {
                    ifrH = 40;
                }
                iframeElem.style.height = ifrH+"px";
            }
            else
            {

            }
        }
        catch(err)
        {

        }
    }
    else
    {
        alert("iframeElem is null");
    }    
}

function scheduleIframeResize(ifrId)
{
    setTimeout("mingleResizeIframeToFitContent('"+ifrId+"')", 2000)
}

function mingleResizeIframeToFitContent(eid)
{
    var iframeElem = document.getElementById(eid);
    if (iframeElem != null)
    {
        //iframeElem.style.width = document.frames[eid].document.body.scrollWidth;
        var ifrH = iframeElem.document.body.scrollHeight;
        if (ifrH < 8 || ifrH > 600)
        {
            ifrH = 285;
        }
        iframeElem.style.height = ifrH;
    }
    
    var widgettable = document.getElementById("widgettable");
    var pHeight = widgettable.scrollHeight + 600;
    if (pHeight > 2000)
    {
        if (FB.CanvasClient)
            FB.CanvasClient.setCanvasHeight(pHeight+"px");
    }
    var bookmarkimg = document.getElementById("bookmarkimg");
    if (bookmarkimg != null)
    {
        bookmarkimg.style.top = (pHeight-36)+"px";
        bookmarkimg.style.visibility = "visible";
    }
}

function AddNewWidget()
{
    if (postAsId == "")
    {
        postAsId = userid;
        postAsName = userFirstName;
        postAsPicUrl = userPicUrl;
    }
    if (htmleditorvisible)
    {
        setEditorHtml();
        AddNewWidgetEx(document.getElementById("editorhtml").value);
    }
    else
    {
        var newWidget = document.getElementById('newwidget');
        if (newWidget.value=='Paste HTML, Embed or Flash' || newWidget.value == "") return;
        AddNewWidgetEx(newWidget.value);
        newWidget.value = 'Paste HTML, Embed or Flash';
        newWidget.style.color = "#aaa";
    }
    parent.bebikiScheduleIframeResize('appblog');
}

function AddNewWidgetEx(widtext)
{
    var escapedWidget = escape(widtext);
    var uniqueid = getRandomID();
    ServerAddEmbed(uniqueid, ownerid, postAsId, escapedWidget);
    var currentTime = new Date()
    var month = currentTime.getMonth() + 1;
    var day = currentTime.getDate();
    var year = currentTime.getFullYear();
    var hours = currentTime.getHours();
    var minutes = currentTime.getMinutes();
    var rDate = month+"/"+day+"/"+year+" "+hours+":"+minutes;
    InsertWidgetAtTop(uniqueid, ownerid, postAsId, postAsName, rDate, widtext);
}
 
var wrowindex = 1;

function InsertWidgetAtTop(uniqueid, wOwnerId, wUserId, mUserFirstName, mDate, widtext)
{   
    var deleteLink = "<span style=\"cursor:pointer;\" onclick=\"DeleteEmbed('" + uniqueid + "')\"><img border=\"0\" title=\"Delete\" src=\"images/deletemessage.gif\" onmouseover=\"this.src='images/deletemessagehi.gif'\" onmouseout=\"this.src='http://Bebiki.com/images/deletemessage.gif'\"/></span>";
    var wHeader = "<table class=\"embpostheader\" width=\"420\"><tr><td align=\"left\" width=\"200\"><a target=\"_parent\" href=\"profile.aspx?id="+wUserId+"\">"+mUserFirstName+"</a></td><td align=\"right\">"+mDate+"&nbsp;" + deleteLink + "</td></tr></table>";
        
    var cellclass1 = "bebiki_cell1";
    var cellclass2 = "bebiki_cell2";
    var cellclass;

    var result = "";
    if (wrowindex % 2 == 0)
        cellclass = cellclass2;
    else
        cellclass = cellclass1;
    
    var widgettable = document.getElementById("widgettable");
    var newRow = widgettable.insertRow(0);
    newRow.id = "widgetrow"+uniqueid;
    newRow.style.height = "50px";
    newAddedWidgetHeight = 50;
    newAddedWidgetRow = newRow;    
    var wcell = newRow.insertCell(0);

    wcell.className = cellclass;
    wcell.style.padding="3px";
    wcell.vAlign = "top";    
    wcell.setAttribute("align","left");    
    wcell.innerHTML = wHeader;
    newAddedWidgetCell = wcell;
    newAddedWidgetId = uniqueid;       
    wrowindex++;
    var embdiv  = document.createElement("DIV");
    embdiv.id = "embdiv"+newAddedWidgetId;
    embdiv.innerHTML = widtext;
    newAddedWidgetCell.appendChild(embdiv);
}


function ServerAddEmbed(uniqueid, ownerid, userid, newhtml)
{
    var params = "uniqueid="+uniqueid+"&ownerid=" + ownerid + "&userid=" + userid + "&widgetbroadcast=" + widgetbroadcast + "&newhtml=" + newhtml;
    makePOSTRequest("addembed.ashx", params, AddEmbedDone);
}

function AddEmbedDone(response)
{
   if (response == "OK")
   {
       //  
   }
   else
   {
      alert(response);
   }   
}

function DeleteEmbed(uniqueid)
{
    var params = "uniqueid="+uniqueid+"&ownerid=" + ownerid;
    makePOSTRequest("removeembed.ashx", params, AddEmbedDone);
    decrementingWidgetRow = document.getElementById("widgetrow"+uniqueid);
    decrementingWidgetRow.cells[0].innerHTML = "";
    decrementingWidgetHeight = 260;
    DecrementWidgetHeight();
}

function DeleteEmbedFromTop(uniqueid, postedBy)
{
    var params = "uniqueid="+uniqueid+"&postedBy=" + postedBy;
    makePOSTRequest("removeembedfromtop.ashx", params, AddEmbedDone);
    decrementingWidgetRow = document.getElementById("widgetrow"+uniqueid);
    decrementingWidgetRow.cells[0].innerHTML = "";
    decrementingWidgetHeight = 260;
    DecrementWidgetHeight();
}

function DeleteEmbedFromLenta(uniqueid, postedBy)
{
    var params = "uniqueid="+uniqueid+"&postedBy=" + postedBy;
    makePOSTRequest("removeembedfromlenta.ashx", params, AddEmbedDone);
    decrementingWidgetRow = document.getElementById("widgetrow"+uniqueid);
    decrementingWidgetRow.cells[0].innerHTML = "";
    decrementingWidgetHeight = 260;
    DecrementWidgetHeight();
}

var decrementingWidgetRow;
var decrementingWidgetHeight;

function DecrementWidgetHeight()
{
    if (decrementingWidgetHeight > 0)
    {
        decrementingWidgetRow.style.height = decrementingWidgetHeight+"px";
        decrementingWidgetHeight -=50;
        setTimeout("DecrementWidgetHeight()",100);
    }
    else
    {
        var widgettable = document.getElementById("widgettable");
        for(var i=0; i<widgettable.rows.length; i++)
        {
            if (widgettable.rows[i].id == decrementingWidgetRow.id)
            {                 
                 widgettable.deleteRow[i];
            }
        }
    }
}

function ViewSourceEmbed(uniqueid, imgElem)
{
        var ielem = document.getElementById("iframe"+uniqueid);
        if (ielem != null)
        {
            if (imgElem.title == "Preview")
            {
                ielem.src = "getwidget.aspx?embid="+uniqueid+"&rb_userid="+ownerid;            
                imgElem.src = "images/coded.gif";
                imgElem.title = "View Source";        
            }
            else
            {
                ielem.src = "getwidget.aspx?embid="+uniqueid+"&rb_userid="+ownerid+"&encode=true";
                imgElem.src = "images/previewd.gif";
                imgElem.title = "Preview";
            }
        }
        else
        {
            var divelem = document.getElementById("embdiv"+uniqueid);
            if (divelem != null)
            {
                if (imgElem.title == "Preview")
                {
                    divelem.innerHTML = unescape(divelem.innerHTML);            
                    imgElem.src = "images/coded.gif";
                    imgElem.title = "View Source";        
                }
                else
                {
                    divelem.innerHTML = escape(divelem.innerHTML);  
                    imgElem.src = "images/previewd.gif";
                    imgElem.title = "Preview";
                }
            }
        }
}

function SelectMessageBroadcast()
{
    messagebroadcast = true;
    document.getElementById("messagebroadcast").style.border="solid 1px red";
    document.getElementById("messageself").style.border="solid 1px #fff";    
}

function SelectMessageSelf()
{
    messagebroadcast = false;
    document.getElementById("messagebroadcast").style.border="solid 1px #fff";
    document.getElementById("messageself").style.border="solid 1px red";    
}

function SelectWidgetBroadcast()
{
    widgetbroadcast = true;
    document.getElementById("widgetbroadcast").style.border="solid 1px red";
    document.getElementById("widgetself").style.border="solid 1px #fff";    
}

function SelectWidgetSelf()
{
    widgetbroadcast = false;
    document.getElementById("widgetbroadcast").style.border="solid 1px #fff";
    document.getElementById("widgetself").style.border="solid 1px red";    
}

function SelectMessage(umid)
{
    var ctr = document.getElementById(selectedRowId);
    if (ctr != null)
    {
        var thisChild = ctr.firstChild;
        while (thisChild != null)
        {
	       if (thisChild.tagName=="TD")
	       {
               thisChild.className = "readmessageitem";
           }
           thisChild = thisChild.nextSibling;
        }
    }
    
    selectedRowId = umid;
    var mtr = document.getElementById(umid);
    if (mtr != null)
    {
        var thisChild = mtr.firstChild;
        while (thisChild != null)
        {
	       if (thisChild.tagName=="TD")
	       {
               thisChild.className = "selected"+thisChild.className;
           }
           thisChild = thisChild.nextSibling;
        }
    }
    var msgbody = document.getElementById("msgbody"+umid);
    
    if (msgbody != null)
    {
        document.getElementById("messagepane").innerHTML = BebikiFormat(msgbody.value);
    }
    var params = "userid="+userid+"&uid="+umid;
    makePOSTRequest("markasread.ashx", params, MarkAsReadDone);
}

function BebikiFormat(ftext)
{
    var encodedMessage = unescape(ftext);
    encodedMessage = encodedMessage.replace(/\r\n/g, "<br>")
    for (var emIx = abrv.length - 1; emIx >= 0; emIx--)
    {
        var strtoreplace = "<img src='emoticons/" + (emIx + 1) + ".gif'>";
        var rwhat = abrv[emIx];
        do
        {
            encodedMessage = encodedMessage.replace(rwhat, strtoreplace);
        }
        while(encodedMessage.indexOf(rwhat) > 0);
    }
    return encodedMessage;
}

function MarkAsReadDone()
{

}

function ReplyToActiveMessage()
{
    document.location="compose.aspx?reply="+selectedRowId;
}

function DeleteActiveMessage()
{
    document.location="inbox.aspx?delete="+selectedRowId;
}

function DeleteSentActiveMessage()
{
    document.location="sent.aspx?delete="+selectedRowId;
}

var selindex = 0;

function SearchFromHeaderKeyDown()
{
        var e = window.event || e;
        var intKey = (window.Event) ? e.which : e.keyCode;
        if (intKey == 13)
        {
            SearchFromHeader();
        }
}

function SearchFromHeader()
{
    var searchtext = document.getElementById("searchtext");
    if (searchtext != null)
    {
        location = "search.aspx?keywords="+searchtext.value;
    }
}

function TypeAhead(e)
{   
    var e = window.event || e;
    var typeaheadselector = document.getElementById("typeaheadselector");
    var typeaheadselectorinput = document.getElementById("typeaheadselectorinput");
    var dropdownbox = document.getElementById("dropdownbox");    
    
    var typedtext = typeaheadselectorinput.value;
    var intKey = (window.Event) ? e.which : e.keyCode;
    if (intKey >=48)
    {
        typedtext = typedtext + String.fromCharCode(intKey);
        selindex = 0;
    }
    else if (intKey==8)
    {
        selindex = 0;
        if (typedtext.length > 1)
        {
            typedtext = typedtext.substring(0, typedtext.length-1);
        }
        else
        {
            dropdownbox.style.display = "none";
            if (typedtext.length == 0)
            {
                var prevSib = typeaheadselectorinput.previousSibling;
                if (prevSib != null)
                {
                    typeaheadselector.removeChild(prevSib);
                    UpdateToIds();
                }
            }
            return;
        }
    }    
         
    
    var typedtextlength = typedtext.length;
    if (typedtextlength == 0)
        return;
   
    var fnids = new Array();
    var lnids = new Array();
            
    for(var i=0;i<idlist.length;i++)
    {           
        if (fnamelist[i].substring(0,typedtextlength).toLowerCase() == typedtext.toLowerCase())
        {
            //dropDownBoxHtml += "<tr class=\""+rclass+"\"><td><img src=\""+piclist[i]+"\" width=\"30\"></td><td><span style=\"font-weight:bold;background-color:#ddd;\">"+fnamelist[i].substring(0, typedtextlength)+"</span>"+fnamelist[i].substring(typedtextlength)+" "+lnamelist[i]+"</td></tr>";
            fnids.push(i);
        } 
        else if (lnamelist[i].substring(0,typedtextlength).toLowerCase() == typedtext.toLowerCase())
        {
            //dropDownBoxHtml += "<tr class=\""+rclass+"\"><td><img src=\""+piclist[i]+"\" width=\"30\"></td><td>"+fnamelist[i]+" <span style=\"font-weight:bold;background-color:#ddd;\">"+lnamelist[i].substring(0, typedtextlength)+"</span>"+lnamelist[i].substring(typedtextlength)+"</td></tr>";
            lnids.push(i);
        }        
    }
    
    if (intKey==40 || intKey==38)
    {            
        if (intKey==40)
        {
            if (selindex < fnids.length + lnids.length - 1)
                selindex++;
        }
        if (intKey==38)
        {
            if (selindex > 0)
                selindex--;
        }
    }else if (intKey == 13)
    {
        if (e.preventDefault) {  e.preventDefault(); } else {e.returnValue = false;}
        dropdownbox.style.display = "none";
        var sId = "";
        var arrIndx = 0;
        if (fnids.length >0 || lnids.length > 0)
        {
            if (selindex >= fnids.length)
            {
                arrIndx = lnids[selindex - fnids.length];
            }
            else
            {
                arrIndx = fnids[selindex];
            }
            sId = idlist[arrIndx]; 
            SelectId(sId, arrIndx);
        }
        return;        
    }
    
    
    var dropDownBoxHtml = "<table>";
    var cindex = 0;
    for(var i=0;i<fnids.length;i++)
    {
        var rclass = "dropdownitem";
        if (cindex == selindex)
            rclass = "selecteddropdownitem";
         var j = fnids[i];   
         dropDownBoxHtml += "<tr onclick=\"SelectId('"+idlist[j]+"', '"+j+"')\" class=\""+rclass+"\"><td><img src=\""+piclist[j]+"\" width=\"30\"></td><td><span style=\"font-weight:bold;background-color:#ddd;\">"+fnamelist[j].substring(0, typedtextlength)+"</span>"+fnamelist[j].substring(typedtextlength)+" "+lnamelist[j]+"</td></tr>";
         cindex++;
    }
    for(var i=0;i<lnids.length;i++)
    {
        var rclass = "dropdownitem";
        if (cindex == selindex)
            rclass = "selecteddropdownitem";
         var j = lnids[i];   
         dropDownBoxHtml += "<tr onclick=\"SelectId('"+idlist[j]+"', '"+j+"')\" class=\""+rclass+"\"><td><img src=\""+piclist[j]+"\" width=\"30\"></td><td>"+fnamelist[j]+" <span style=\"font-weight:bold;background-color:#ddd;\">"+lnamelist[j].substring(0, typedtextlength)+"</span>"+lnamelist[j].substring(typedtextlength)+"</td></tr>";         
         cindex++;
    }
                    
    dropDownBoxHtml += "</table>";
    dropdownbox.innerHTML = dropDownBoxHtml;
    dropdownbox.style.display="block";
        
}

function SelectId(sid, indx)
{
    var typeaheadselector = document.getElementById("typeaheadselector");
    var dropdownbox = document.getElementById("dropdownbox");
    var typeaheadselectorinput = document.getElementById("typeaheadselectorinput");
    typeaheadselectorinput.value = "";
    dropdownbox.style.display = "none";
    
    if (document.getElementById("nameitem"+sid) == null)
    {                 
        var newElem = document.createElement("SPAN");
        newElem.className = "nameitem";
        newElem.id="nameitem"+sid;
        newElem.innerHTML = fnamelist[indx]+"&nbsp;"+lnamelist[indx]+"<img src=\"images/deletemessage.gif\" onmouseover=\"this.src='images/deletemessagehi.gif'\" onmouseout=\"this.src='images/deletemessage.gif'\" onclick=\"deletenameitem('nameitem"+sid+"')\">";
        typeaheadselector.insertBefore(newElem, typeaheadselectorinput);
        UpdateToIds();
    }
}

function deletenameitem(itemid)
{
    var item = document.getElementById(itemid);    
    if (item != null)
    {
        var typeaheadselector = document.getElementById("typeaheadselector");
        typeaheadselector.removeChild(item);
        UpdateToIds();
    }
}

function UpdateToIds()
{
        var toids = document.getElementById("toids");
        var typeaheadselector = document.getElementById("typeaheadselector");
        if (toids != null && typeaheadselector != null)
        {
            toids.value = "";
            var thisChild = typeaheadselector.firstChild;
            while (thisChild != null)
            {
	           if (thisChild.className=="nameitem")
	           {
                   toids.value += thisChild.id.substring(8)+",";
               }
               thisChild = thisChild.nextSibling;
            }
            
            if (toids.value.length>0)
                toids.value = toids.value.substring(0,toids.value.length-1);
                            
        }
}

function SetPageStatus(statusstring)
{
    var statusbar = document.getElementById("pagestatusbar");
    if (statusstring == "")
    {
       statusbar.style.visibility = "hidden";
    }
    else
    {
       statusbar.style.visibility = "visible";
       statusbar.innerHTML = statusstring;
    }
}

function flyrequests(items)
{
    for(var i=0; i<items.length; i++)
    {
        flyone(items[i]);
    }
    //setTimeout("getirequests()", 15000);
}

function getirequests()
{
    if (userid)
    {
        makePOSTRequest("getirequests.ashx?userid="+userid, "", getirequestsDone);
    }
}

function getirequestsDone(result)
{
    try {
        var resultArr = eval( result );
        for(var i=0; i<resultArr.length; i++)
        {
           flyone(resultArr[i]);
        }  
    } catch (err) 
    {
        //alert(err.description + " " + result);
    }
    //setTimeout("getirequests()", 15000);
}

function flyone(ritem)
{
    var flyer = document.getElementById("flyer");
    var newElem = document.createElement("SPAN");
    newElem.id = "fly"+ritem.rid;
    newElem.className="requestspan";
    newElem.style.position = "relative";
    newElem.style.left = "700px";
    flyitemleft = 700;
    newElem.innerHTML = ritem.rfrom + " invites you to " + ritem.rtype + "- <a href=\"#\" onclick=\"acceptRequest('"+ritem.rid+"', '"+ritem.rfromid+"')\"><b>Accept</b></a> | <a href=\"#\" onclick=\"ignoreRequest('"+ritem.rid+"')\">Ignore</a></span>";
    flyer.appendChild(newElem);
    setTimeout("moveflyitem('"+ritem.rid+"')",100);
}

var flyitemleft = 700;

function moveflyitem(fid)
{
    var flyitem = document.getElementById("fly"+fid);
    if (flyitemleft > 0)
    {
        flyitemleft = flyitemleft - 50;
        flyitem.style.left = flyitemleft+"px";
        setTimeout("moveflyitem('"+fid+"')",50);
    }
    else
    {
        var flyer = document.getElementById("flyer");
        var requests = document.getElementById("requests");
        flyer.removeChild(flyitem);
        var fChild = requests.firstChild;
        if (fChild == null)
        {
            requests.appendChild(flyitem);
        }
        else
        {
            requests.insertBefore(flyitem, fChild);
        }    
    }    
}

function acceptRequest(rid, fromid)
{
    var flyitem = document.getElementById("fly"+rid);
    var flyitemparent = flyitem.parentNode;
    flyitemparent.removeChild(flyitem);
    window.open("chat.aspx?userid="+userid+"&accept=true&rid="+rid,"chatwindow"+fromid,"menubar=0,resizable=0,left=400,top=200,width=450,height=500");
    return false;
}

function ignoreRequest(rid)
{
    var flyitem = document.getElementById("fly"+rid);
    var flyitemparent = flyitem.parentNode;
    flyitemparent.removeChild(flyitem);
    makePOSTRequest("ignorerequest.ashx?userid="+userid+"&rid="+rid, "", aiRequestDone);
    return false;
}

function aiRequestDone()
{

}

function inviteToChat(inviteid)
{
    window.open("chat.aspx?userid="+userid+"&inviteid="+inviteid,"chatwindow"+inviteid,"menubar=0,resizable=0,left=400,top=200,width=450,height=500");
    return false;
}

var htmleditorvisible = true;
function ShowHtmlEditor()
{
    var tarea = document.getElementById("textarea");
    var htmleditor = document.getElementById("htmleditor");
    var uploadimage = document.getElementById("uploadimage");

    tarea.style.display="none";
    tarea.style.visibility = "hidden";

    uploadimage.style.display="none";
    uploadimage.style.visibility = "hidden";
    
    htmleditor.style.display="block";
    htmleditor.style.visibility = "visible";

    document.getElementById("textareatab").className = "menutab";
    document.getElementById("htmleditortab").className = "menutabS";        
    document.getElementById("uploadimagetab").className = "menutab";  
    htmleditorvisible = true;
    document.getElementById("posttable").style.visibility = "visible";
}

function ShowTextarea()
{
    var tarea = document.getElementById("textarea");
    var htmleditor = document.getElementById("htmleditor");
    var uploadimage = document.getElementById("uploadimage");

    htmleditor.style.display="none";
    htmleditor.style.visibility = "hidden";

    uploadimage.style.display="none";
    uploadimage.style.visibility = "hidden";
    
    tarea.style.display="block";
    tarea.style.visibility = "visible";

    document.getElementById("textareatab").className = "menutabS";
    document.getElementById("htmleditortab").className = "menutab";        
    document.getElementById("uploadimagetab").className = "menutab";  
    htmleditorvisible = false;
    document.getElementById("posttable").style.visibility = "visible";
}

function ShowUploadImage()
{
    var tarea = document.getElementById("textarea");
    var htmleditor = document.getElementById("htmleditor");
    var uploadimage = document.getElementById("uploadimage");

    htmleditor.style.display="none";
    htmleditor.style.visibility = "hidden";

    tarea.style.display="none";
    tarea.style.visibility = "hidden";
    
    uploadimage.style.display="block";
    uploadimage.style.visibility = "visible";

    document.getElementById("uploadimagetab").className = "menutabS";  
    document.getElementById("textareatab").className = "menutab";
    document.getElementById("htmleditortab").className = "menutab";        
    htmleditorvisible = false;
    document.getElementById("posttable").style.visibility = "hidden";
}

function TogglePostDropDown(bid)
{
     var bebikipostbuttondropdown = document.getElementById("postbuttondropdown"+bid);
     if (bebikipostbuttondropdown.style.visibility=="hidden")
     {    
         bebikipostbuttondropdown.style.visibility='visible';
         bebikipostbuttondropdown.style.display='block';
     }
     else
     {    
         bebikipostbuttondropdown.style.visibility='hidden';
         bebikipostbuttondropdown.style.display='none';     
     }     
}

function HidePostDropDown()
{
//     if (event.srcElement!= event.toElement.parentElement)
//     {
//         var bebikipostbuttondropdown = document.getElementById("postbuttondropdown");
//         if (bebikipostbuttondropdown.style.visibility=="visible")
//         {   
//             bebikipostbuttondropdown.style.visibility='hidden';
//             bebikipostbuttondropdown.style.display='none';     
//         }
//     }     
}

var postAsId = "";
var postAsName = "";
var postAsPicUrl = "";
function CloseAndPostAs(buttonId, postasid, postasname, postaspicurl, onpostptr)
{
     postAsId = postasid;
     postAsName = postasname;
     postAsPicUrl = postaspicurl
     if (postAsId == "")
        postAsId = userid;
     var bebikipostbuttondropdown = document.getElementById("postbuttondropdown"+buttonId);
     bebikipostbuttondropdown.style.visibility='hidden';
     bebikipostbuttondropdown.style.display='none';
     var fc = new Function(onpostptr);
     fc();
}

function SubmitNewThreadForm()
{
    if (postAsId == "")
        postAsId = userid;
    document.getElementById("uniqueid").value = getRandomID();
    setEditorHtml();
    document.getElementById("newdiscussion").value = document.getElementById("editorhtml").value;
    document.getElementById("newthreadpostasid").value = postAsId;
    document.forms["newthreadform"].submit();
}

function UpdateStatus()
{
    var currentstatus = document.getElementById("currentstatustext").value;
    document.getElementById("statuseditor").style.visibility = "hidden";
    document.getElementById("statuseditor").style.display = "none";
    document.getElementById("currentstatus").innerHTML = currentstatus;
    document.getElementById("currentstatus").style.visibility = "visible";
    document.getElementById("statuschangelink").style.visibility = "visible";    
    newbebistatus = currentstatus;
    var parames = "userid="+userid+"&ownerid=" + ownerid + "&currentstatus=" + escape(newbebistatus);
    makePOSTRequest("updatestatus.ashx", parames, UpdateStatusDone);
}
var newbebistatus = "";

function UpdateStatusDone(result)
{
    if (result=="OK")
    {
        if (newbebistatus != "")
        {
            publishStatus(ownerid, ownerFirstName, ownerBigPicUrl, newbebistatus);
        }
    }
    else
    {
        alert(result);
    }
}

function OpenStatusEditor()
{
    document.getElementById("statuseditor").style.visibility = "visible";
    document.getElementById("statuseditor").style.display = "block";
    document.getElementById("currentstatus").style.visibility = "hidden";
    document.getElementById("statuschangelink").style.visibility = "hidden";
    document.getElementById("currentstatustext").value = 
        document.getElementById("currentstatus").innerHTML;
    document.getElementById("currentstatustext").focus();
}

function accesstypechanged()
{
    var passcodetr = document.getElementById("passcodetr");
    var accesstype = document.getElementById("accesstype");

    if (accesstype.value=="PasscodeProtected")
    {
        passcodevisible = true;
        passcodetr.style.display="block";
    }
    else
    {
        passcodevisible = false;
        passcodetr.style.display = "none";
    }
}
var messageboardvisible = false;

function ToggleNewMessage()
{
    if (messageboardvisible)
    {
        messageboardvisible = false;
        document.getElementById("plusminusicon").src = "images/plusicon.png";
        document.getElementById("plusminusspan").innerHTML = "Post New Message";
        document.getElementById("newmessageboard").style.display = "none";
        document.getElementById("newmessagebutton").style.display = "none";
        document.getElementById("newmessagepic").style.display = "none";
        
    }
    else
    {
        messageboardvisible = true;
        document.getElementById("plusminusicon").src = "images/minusicon.png";
        document.getElementById("plusminusspan").innerHTML = "Hide Message Board";
        document.getElementById("newmessageboard").style.display = "block";
        document.getElementById("newmessagebutton").style.display = "block";
        document.getElementById("newmessagepic").style.display = "block";

    }
}

function publishItemILike(userid, username, itemsrc, itemid, itemcomment) {
    
    if (!inFacebook)
    {
        top.location = appCanvasUrl;
        return;
    }    
    var itemlink = appCanvasUrl;
    if (itemid != "")
        itemlink += "/comments.aspx?itemid="+itemid;
        
    var tpl_data ={"images":[{"src":itemsrc,"href":itemlink}],"bebiid":userid,"bebiname":username, "itemcomment":itemcomment};
    var user_msg = {"value":"Lol"};
    var share_msg = "Publish on Facebook News Feeds";
       
    try
    {
      FB.ensureInit(function() {
        FB.Connect.showFeedDialog(108308105919, tpl_data, "", "", null, share_msg, user_msg);
      });
    
    }catch(err){alert(err)};    
} 

var emailboard = null;

function SendEmailToAFriend(embid)
{
    var ebox = document.getElementById("emailbox" + embid).value;
    
    if (ebox != "")
    {
        emailboard = document.getElementById("emailboard" + embid);
        emailboard.innerHTML = "sending mail...";
        var paramems = "senderid=" + userid + "&sendername=" + userFirstName + "&embid=" + embid + "&ebox=" + ebox;
        makePOSTRequest("sendemail.ashx", paramems, SendEmailDone);
    }
}

function SendEmailDone(result)
{
    if (result=="OK")
    {
        if (emailboard != "")
        {
           emailboard.innerHTML = "email successfully sent.";
        }
    }
    else
    {
        emailboard.innerHTML = result;
    }
}

function ShowPages(selfilename)
{
    document.getElementById("resourcesfooter").style.display = "none";
    document.getElementById("pagesfooter").style.display = "block";
    
    document.getElementById("pagestab").className = "menutabS";
    document.getElementById("resourcestab").className = "menutab";
    document.getElementById("respages").innerHTML = "loading...";
    makePOSTRequest("getpages.ashx", "id="+appid+"&sname="+selfilename, PRDone);
}

function ShowResources()
{
    document.getElementById("resourcesfooter").style.display = "block";
    document.getElementById("pagesfooter").style.display = "none";
    
    document.getElementById("pagestab").className = "menutab";
    document.getElementById("resourcestab").className = "menutabS";
    document.getElementById("respages").innerHTML = "loading...";
    makePOSTRequest("getresources.ashx", "id="+appid, PRDone);
}

function abreviate(aname)
{
    if (aname.length>13)
    {
        return aname.substring(0,5)+".."+aname.substring(aname.length-6);
    }
    else
    {
        return aname;
    }
}

function cleanErrorMessage()
{
    document.getElementById("errormsg").innerHTML = "&nbsp;";
}
        
function PRDone(result)
{
    document.getElementById("respages").innerHTML = result;
}

var readmorestatus = false;
function ReadMore()
{
    if (readmorestatus)
    {
        document.getElementById("readmore1").style.display = "none";
        document.getElementById("readmorebutton1").innerHTML = "read more...";
        document.getElementById("readmore2").style.display = "none";
        document.getElementById("readmorebutton2").innerHTML = "read more...";
        document.getElementById("readmore3").style.display = "none";
        document.getElementById("readmorebutton3").innerHTML = "read more...";
        document.getElementById("readmore4").style.display = "none";
        document.getElementById("readmorebutton4").innerHTML = "read more...";
        readmorestatus = false;
    }
    else
    {
        document.getElementById("readmore1").style.display = "block";
        document.getElementById("readmorebutton1").innerHTML = "<< ";
        document.getElementById("readmore2").style.display = "block";
        document.getElementById("readmorebutton2").innerHTML = "<< ";
        document.getElementById("readmore3").style.display = "block";
        document.getElementById("readmorebutton3").innerHTML = "<< ";
        document.getElementById("readmore4").style.display = "block";
        document.getElementById("readmorebutton4").innerHTML = "<< ";
        readmorestatus = true;
    }    
}

function FocusSearchInput()
{
    var qinput = document.getElementById(qinput);
    if (qinput != null)
        qinput.focus();
}

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

