var checkPresence = 0;
var avtar1 = '../static/images/newUserImg.png';
var ms = 0;
var state = 0;
var ssbutton;
var transaction_id = 0;
var ms2=0;
var position1;
var company1;
var skypeid1;
var tc;
var Expert_Status='';
var state1 =0;

var hire1;
var myUserId;
var otherUserId;
var initialJSJaCMessage;
var msgBlinkTimer = null;
var lastWindowTitle;
var hasWindowFocus = true;
var lastMessageSenderName=[[],[]];
var arDhtmlWindows=[[],[]];
var documentHeight = 1;
var documentWidth = 1;
var btnTextColor="#004080";


var showWarningMessageForFunds = true;
var nextReconnectTimer = null;
var retryAttemptCount = 0;
var nextReconnectMS = 3 * 1000; // Three Seconds

var backend="binding";
var user,password,httpBase,localDomain;




/***** Billing Variables*****/
var xPackets=[[],[]];
var xBillingData=[[],[]];
var balCheckTimer = null;

function billingData()
{
    var serviceStartTime;
    var billingTranId;
    var earnedMoney;
    var earnedMoneyEzdia;
    var totalServiceDurationMs = 0;
    var billingSubject = "";
    var hndUpdateTimer;
    var tmpxPackets;
    var tmpJSJaCPacket;
    var lastSyncTime;
}
var myBalance = 0;
var currentWinRemoteUserId;
/******************XMPP Communication Starts********************/


function handleIQ(aIQ) {
    /*document.getElementById(iResp).innerHTML +=
    "<div class='msg'>IN (raw): " +aIQ.xml().htmlEnc() + '</div>';
  document.getElementById(iResp).lastChild.scrollIntoView();*/
    oDbg.log("IQ :" + aIQ.xml().htmlEnc());
    con.send(aIQ.errorReply(ERR_FEATURE_NOT_IMPLEMENTED));
}



function handlePresence(aJSJaCPacket) {
  
}

function handleError(e) {
    var errorMsg = "An error occured:<br />"+
    ("Code: "+e.getAttribute('code')+"\nType: "+e.getAttribute('type')+
        "\nCondition: "+e.firstChild.nodeName).htmlEnc();
    //document.getElementById('err').innerHTML =  errorMsg;
    oDbg.log(errorMsg);
    // if (con.connected()) {
    //     con.disconnect();
    // }

    //Reconnect to server.
    if (retryAttemptCount <= 3 && nextReconnectTimer == null)// Only retry to connect three times.
    {
        //alert("Retry Attempt# " + retryAttemptCount + "," + nextReconnectMS);
        retryAttemptCount = retryAttemptCount +1;
        //nextReconnectTimer = setTimeout("doLogin('" + user + "','" + password + "','" + httpBase + "','" + localDomain + "');", nextReconnectMS);
        nextReconnectTimer = setTimeout("doReconnect();", nextReconnectMS);
        nextReconnectMS = nextReconnectMS * 10;// Increase login attempt by 10 times.
    }
    else
    {
        var login_chat = document.getElementById('login_chat');
        if (login_chat)
        {
            login_chat.style.display="";
        }
        var logout_chat = document.getElementById('logout_chat');
        if (logout_chat)
        {
            logout_chat.style.display="none";
        }
        if (con.connected()) {
            con.disconnect();
        }

    }
	
}

function handleStatusChanged(status) {
    oDbg.log("status changed: "+status);
}

function handleConnected() {
    document.getElementById('err').innerHTML = '';
    con.send(new JSJaCPresence());
    oDbg.log("connected");
    nextReconnectMS = 3 * 1000;//Three Seconds
    retryAttemptCount = 0;
    if (nextReconnectTimer)
    {
        clearTimeout(nextReconnectTimer);
        nextReconnectTimer = null;
    }
}

function handleDisconnected() {
    try
    {
        var login_chat = document.getElementById('login_chat');
        if (login_chat)
        {
            login_chat.style.display="";
        }
        var logout_chat = document.getElementById('logout_chat');
        if (logout_chat)
        {
            logout_chat.style.display="none";
        }
    }
    catch (ex){	}
    oDbg.log("disconnected");
}

function handleIqVersion(iq) {
    con.send(iq.reply([
        iq.buildNode('name', 'ezdia'),
        iq.buildNode('version', JSJaC.Version),
        iq.buildNode('os', navigator.userAgent)
        ]));
    return true;
}

function handleIqTime(iq) {
    var now = new Date();
    con.send(iq.reply([iq.buildNode('display',
        now.toLocaleString()),
    iq.buildNode('utc',
        now.jabberDate()),
    iq.buildNode('tz',
        now.toLocaleString().substring(now.toLocaleString().lastIndexOf(' ')+1))
    ]));
    return true;
}

function handleMessage(aJSJaCPacket) {
    try
    {
        var html = '';
        var user =aJSJaCPacket.getFromJID();
        var type = aJSJaCPacket.getType();
        var tran_id;
        if (type == 'error') {
            var x;
            for (var i=0; i<aJSJaCPacket.getNode().getElementsByTagName('x').length; i++){
                if (aJSJaCPacket.getNode().getElementsByTagName('x').item(i).getAttribute('xmlns') == 'ezdia:xmpp:billing') {
                    x = aJSJaCPacket.getNode().getElementsByTagName('x').item(i);
                    break;
                }
            }
            if ( x ) // Process chat billing packet failure
            {
                processBillingMessageError(user._node, x);
            }
            else // Process chat message failure
            {
                addMessageDeliveryFailureMsg(user._node,"Failed to deliver the message, Please try again.");
            }
            return;
        }
        if ( user.toString().indexOf("@") == -1 ) { //That means its a Broadcast message.
            handleBroadcastMessage(aJSJaCPacket.getBody());
            return;
        }
        var flag = false;//checkInGroup(user._node, "");

        //alert(user._node);
        if(flag){
            if( aJSJaCPacket.getFromJID() != null ) {
                var chatBody = user._node + 'chatBody';
                var chatID = document.getElementById(chatBody);
                if (!chatID) {
                    getUserData('getUserData.do',user._node,aJSJaCPacket,1);
                }
                processXMPPMessage(chatwith, aJSJaCPacket);
            }

        // html += '<div class="chatuser username2">' + chatwith + '</div>';
        }
        else if(checkInChatGroup(user._node,aJSJaCPacket)){

        //  html += '<div class="chatuser username2">' + chatwith + '</div>';
        }else{
            getUserData('getUserData.do',user._node,aJSJaCPacket,1);
        //  html += '<div class="chatuser username2">' + chatwith + '</div>';
        }
    }
    catch (e) //Ignore Message Exception if any
    {
    }
}


function setupCon(con) {
    con.registerHandler('message',handleMessage);
    con.registerHandler('presence',handlePresence);
    con.registerHandler('iq',handleIQ);
    con.registerHandler('onconnect',handleConnected);
    con.registerHandler('onerror',handleError);
    con.registerHandler('status_changed',handleStatusChanged);
    con.registerHandler('ondisconnect',handleDisconnected);
    con.registerIQGet('query', NS_VERSION, handleIqVersion);
    con.registerIQGet('query', NS_TIME, handleIqTime);
}
/******************XMPP Communication Ends**********************/

/******************Chat Part Starts*************************/

function processBillingMessageError(user, xPkt)
{
    if (xPkt.getAttribute("a") == "hire")
    {
        addMessageDeliveryFailureMsg(user,"Failed to send hire request, Please try again.");
        var hireBtn = document.getElementById(user+'hireBtn');
        if (hireBtn){
            hireBtn.style.display = '';
        }
    }
    else if (xPkt.getAttribute("a") == "rpause")
    {
        addMessageDeliveryFailureMsg(user,"Failed to send Pause request, Please try again.");
        var hireBtn = document.getElementById(user+'hireBtn');
        if (hireBtn){
            hireBtn.style.display = '';
        }
    }
}
//Process xmpp message. Make sure all UI tasks have taken kare before callling this function.
function processXMPPMessage(fromName, aJSJaCPacket)
{
    var x;
    for (var i=0; i<aJSJaCPacket.getNode().getElementsByTagName('x').length; i++){
        if (aJSJaCPacket.getNode().getElementsByTagName('x').item(i).getAttribute('xmlns') == 'ezdia:xmpp:billing') {
            x = aJSJaCPacket.getNode().getElementsByTagName('x').item(i);
            break;
        }
    }

    if ( x ) //If *x* is present in the message then process it for billing.
    {
        otherUserId = aJSJaCPacket.getFromJID().getNode();
        if ( x.getAttribute("a") != "pong" && x.getAttribute("a") != "ping") // Don't Consider ping and pong messages.
        {
            xPackets[aJSJaCPacket.getFromJID().getNode()] = x;
        }
		
        if ( x.getAttribute("a") == "hire" ){
            handleHireRequest(fromName, aJSJaCPacket, x);
            var userId = aJSJaCPacket.getFromJID().getNode();
            if (arDhtmlWindows[userId] && arDhtmlWindows[userId].style.display == "none")
            {
                arDhtmlWindows[userId].show(arDhtmlWindows[userId]);
            }
        }
        else if ( x.getAttribute("a") == "cancel" ){
            handleCancelRequest(fromName, aJSJaCPacket, x);
        }
        else if ( x.getAttribute("a") == "busy" ){
            handleBusyResponse(fromName, aJSJaCPacket, x);
        }
        else if ( x.getAttribute("a") == "rate" ){
            handleRate(fromName, aJSJaCPacket, x);
        }
        else if ( x.getAttribute("a") == "agree" ){
            handleAgree(fromName, aJSJaCPacket, x);
        }
        else if ( x.getAttribute("a") == "disagree" ){
            handleDisagree(fromName, aJSJaCPacket, x);
        }
        else if ( x.getAttribute("a") == "propose" ){
            handlePropose(fromName, aJSJaCPacket, x);
        }
        else if ( x.getAttribute("a") == "nragree" ){
            handleNewRateAgree(fromName, aJSJaCPacket, x);
        }
        else if ( x.getAttribute("a") == "nrdisagree" ){
            handleNewRateDisAgree(fromName, aJSJaCPacket, x);
        }
        else if ( x.getAttribute("a") == "start" ){
            handleStart(fromName, aJSJaCPacket, x);
        }
        else if ( x.getAttribute("a") == "stop" ){
            handleStop(fromName, aJSJaCPacket, x);
        }
        else if ( x.getAttribute("a") == "rpause" ){
            handleRequestPause(fromName, aJSJaCPacket, x);
        }
        else if ( x.getAttribute("a") == "pagree" ){
            handlePauseAgree(fromName, aJSJaCPacket, x);
        }
        else if ( x.getAttribute("a") == "pdisagree" ){
            handlePauseDisagree(fromName, aJSJaCPacket, x);
        }
        else if ( x.getAttribute("a") == "resume" ){
            handleResumeService(fromName, aJSJaCPacket, x);
        }
        else if ( x.getAttribute("a") == "ping" ){
            handlePing(fromName, aJSJaCPacket, x);
        }
        else if ( x.getAttribute("a") == "pong" ){
            handlePong(fromName, aJSJaCPacket, x);
        }
        clearUserBalanceChecker();// Clear this timer if running
    }
    else //Its a normal XMPP Chat Message.
    {
        var user =aJSJaCPacket.getFromJID();
        var type = aJSJaCPacket.getType();
        addMessageToChatWindow(fromName, user.getNode(), aJSJaCPacket.getBody().htmlEnc());
    }
}

//Handle incoming hire request from Explorer to Expert
function handleHireRequest(fromName, aJSJaCPacket, x)
{
    if (allowMultipleHire() == false)
    {
        var aMsg = buildJSCACMessage(aJSJaCPacket.getFromJID().getNode() + "@" + con.domain, "");
        aMsg = buildEzdiaXmppPacket(aMsg,myUserId,aJSJaCPacket.getFromJID().getNode(),null,null,null,null,null,"busy");
        con.send(aMsg);
        var html = "<div class='chatuseragree'>" + getCurrentTime() + "<br>Hire request from "+fromName+" rejected.</div>";
        addInfoToChatWindow(aJSJaCPacket.getFromJID().getNode(), html);
        return;
    }
    xBillingData[aJSJaCPacket.getFromJID().getNode()] = new billingData();
    var infoHtml = "<div class='chatuseragree'>" + getCurrentTime() + "<br>Request from "+fromName+" to hire you.</div>";
    addInfoToChatWindow(aJSJaCPacket.getFromJID().getNode(), infoHtml);
    xBillingData[aJSJaCPacket.getFromJID().getNode()].billingSubject = aJSJaCPacket.getBody();
    var tmpMsg = fromName + " wants to hire you<br /><br />If you wants to continue click Agree<br /><br />Subject: "+aJSJaCPacket.getBody()+"<br /><br />Select the category from next screen according to the subject and send the rate.";
    xBillingData[aJSJaCPacket.getFromJID().getNode()].tmpJSJaCPacket = aJSJaCPacket;
	
    var billingWinId = aJSJaCPacket.getFromJID().getNode() + "BillingRoot";
    var billingWnd = document.getElementById(billingWinId);
    billingWnd.innerHTML = getIncomingHireRequestUI(aJSJaCPacket.getFromJID().getNode(), tmpMsg);
    billingWnd.style.display ='';

}

function agreeForHireRequest(userId)
{
    xBillingData[userId].totalServiceDurationMs = 0;
    ms = 0;
    //Open Billing window and add Rate div to it.
    var billingWinId = userId + "BillingRoot";
    var billingWnd = document.getElementById(billingWinId);
    billingWnd.innerHTML = getBillingRequestUI(userId, xBillingData[userId].tmpJSJaCPacket.getBody().htmlEnc());
    billingWnd.style.display ='';
    var hireBtnIfAny = document.getElementById(userId+'hireBtn');
    if (hireBtnIfAny) {
        hireBtnIfAny.style.display = 'none';
    } // Hide Hire button if any
    getMyExpertise(userId + 'Category');
    getUserAccountBalance(null);// Query user balance from server.
}

function handleBusyResponse(fromName, aJSJaCPacket, x)
{
    var infoHtml = "<div class='chatuseragree'>" + fromName+" is busy.</div>";
    addInfoToChatWindow(aJSJaCPacket.getFromJID().getNode(), infoHtml);
    var hireBtn = document.getElementById(aJSJaCPacket.getFromJID().getNode()+'hireBtn');
    if (hireBtn)// If hire button available then enable it
    {
        hireBtn.style.display = 'block';
    }
}

// Handle cancel request for hire. Can come from both side expert and explorer.
function handleCancelRequest(fromName, aJSJaCPacket, x)
{
    var infoHtml = "";
    if ( x.getAttribute("e") == myUserId )// Cancel request coming from Explorer
    {
        infoHtml = "<div class='chatuseragree'>" + getCurrentTime() + "<br>"+fromName+" Cancelled the request.</div>";
    }
    else
    {
        infoHtml = "<div class='chatuseragree'>" + getCurrentTime() + "<br>"+fromName+" Cancelled the request sent to hire.</div>";
    }
	
    addInfoToChatWindow(aJSJaCPacket.getFromJID().getNode(), infoHtml);
    var hireBtn = document.getElementById(aJSJaCPacket.getFromJID().getNode()+'hireBtn');
    if (hireBtn)// If hire button available then enable it
    {
        hireBtn.style.display = 'block';
    }
    if ( document.getElementById(aJSJaCPacket.getFromJID().getNode() + 'BillingRoot') )//If billing window is opened then hide it.
    {
        hideBillingLayer(aJSJaCPacket.getFromJID().getNode() + 'BillingRoot');
    }
}

//Handle Rate coming form expoet to explorer.
function handleRate(fromName, aJSJaCPacket, x)
{
    //Open Billing window and add Rate div to it.
    var billingWinId = aJSJaCPacket.getFromJID().getNode() + "BillingRoot";
    var billingWnd = document.getElementById(billingWinId);
    billingWnd.innerHTML = getRateUI(aJSJaCPacket.getFromJID().getNode(), x, null);
    billingWnd.style.display ='';
}

//Handle agree for rates sent by expert. 
function handleAgree(fromName, aJSJaCPacket, x)
{
    var html;
    if (x.getAttribute("t") == "fix")
    {
        html= "<div class='chatuseragree'>" + fromName + " agree for your fix rate " + x.getAttribute("fr") + " $</div>";
    }
    else
    {
        html= "<div class='chatuseragree'>" + fromName + " agree for your rate " + x.getAttribute("vr") + " $ per min</div>";
    }
    addInfoToChatWindow( aJSJaCPacket.getFromJID().getNode(), html);
    var billingWinId = aJSJaCPacket.getFromJID().getNode() + "BillingRoot";
    var billingWnd = document.getElementById(billingWinId);
    billingWnd.innerHTML = getServiceUIForExpert(aJSJaCPacket.getFromJID().getNode(),xPackets[aJSJaCPacket.getFromJID().getNode()],false);
    billingWnd.style.display ='';
}
//Handle disagree to rates sent by expert
function handleDisagree(fromName, aJSJaCPacket, x)
{
    var html;
    if (x.getAttribute("t") == "fix")
    {
        html= "<div class='chatuseragree'>" + fromName + " disagree for your fix rate " + x.getAttribute("fr") + " $</div>";
    }
    else
    {
        html= "<div class='chatuseragree'>" + fromName + " disagree for your rate " + x.getAttribute("vr") + " $ per min</div>";
    }
    addInfoToChatWindow( aJSJaCPacket.getFromJID().getNode(), html);
}
//Handle new rates proposed by explorer to expert.
function handlePropose(fromName, aJSJaCPacket, x)
{
    var infohtml;
    var confirmMsg;
    var userId = aJSJaCPacket.getFromJID().getNode();
    xBillingData[userId].tmpJSJaCPacket = aJSJaCPacket;
    xBillingData[userId].tmpxPackets = x;
    if ( x.getAttribute("e") == myUserId )
    {
        if ( x.getAttribute("t") == "fix" ){
            infohtml = "<div class='chatuseragree'>" + fromName + " proposed new rate<br />Explorer Price : " + x.getAttribute("nr") + " $ </div>";
            confirmMsg = fromName + " proposed new rate<br />Explorer Price : " + x.getAttribute("nr") + " $<br /><br />Do you want to continue?";
        }
        else {
            infohtml = "<div class='chatuseragree'>" + fromName + " proposed new rate<br />Explorer Price : " + x.getAttribute("nr") + " $ per min</div>";
            confirmMsg = fromName + " proposed new rate<br />Explorer Price : " + x.getAttribute("nr") + " $ per min<br /><br />Do you want to continue?";
        }
        addInfoToChatWindow(userId, infohtml);
		
        var html = '<div style="width: 557px; height: auto;">';
        html += '<table id="corner_dialog_table0" align="center" class="corner_dialog_table" style="width: 100%; height: auto;">';
        html += '<tr>';
        html += '<td class="corner_topleft_green"></td>';
        html += '<td class="corner_topborder_green"></td>';
        html += '<td class="corner_topright_grn"></td>';
        html += '</tr>';
        html += '<tr>';
        html += '<td class="corner_borderleft_green"></td>';
        html += '<td id="corner_content_grn0" class="corner_content_grn">';
        html += '<div id="checkoutid"style="width: 100%; height: auto;">';
        html += '<div class="popup-header global-bg-color" style="position:relative; width:539px; margin-left:-10px; margin-top:-10px;">';
        html += '<div style="font-size:14px;">';
        html += 'Proposed Rate';
        html += '<div style="cursor: pointer; position: absolute; font-size: 9px; font-weight: bold; right: 10px; width: auto; top: 10px;">';
        //html += '<a href="javascript:void(0);" id="loginpopup_closeimg" onclick="closecommonconn()" style="color: white;">Close X</a>';
        html += '</div>';
        html += '</div>';
        html += '</div>';
        html += '<div id="CashierInnerDiv">';
        html += '<div class="row" style="padding-top:10px;"><div class="cell nml_bluetxt" style="width:100%;text-align:left;">' + confirmMsg + '</div></div>';
        html += '<div class="row" style="padding-top:20px; height:40px;">';
        html += '<div class="cell" style="width:110px; margin-left: 140px;">';
        html += '<a href="javascript:void(0)" class="global-button global-color small-button-padding" onclick="handlePropose_Agree(\''+userId+'\',\''+fromName+'\')">';
        html += 'Yes';
        html += '</a>';
        html += '</div>';
        html += '<div class="cell" style="width:110px;">';
        html += '<a href="javascript:void(0)" class="global-button global-color small-button-padding" onclick="handlePropose_Disagree(\''+userId+'\');">';
        html += 'No';
        html += '</a>';
        html += '</div>';
        html += '</div>';
        html += '</div>';
        html += '</div>';
        html += '</td>';
        html += '<td class="corner_border_right_grn"></td>';
        html += '</tr>';
        html += '<tr>';
        html += '<td class="corner_bottomleft_grn"></td>';
        html += '<td class="corner_border_bottom_grn"></td>';
        html += '<td class="corner_bottomright_grn"></td>';
        html += '</tr>';
        html += '</table>';
        html += '</div>';



        lid = "ConnectionPopUp";

        commoncallback(html, "ConnectionPopUp");
		
    }
    else
    {

}
	
}

function handlePropose_Agree(userId, fromName)
{
    var aMsg = buildJSCACMessage(userId + "@" + con.domain, "ezd");
    var x = xBillingData[userId].tmpxPackets;
    if ( x.getAttribute("t") == "fix" )
    {
        aMsg = buildEzdiaXmppPacket(aMsg,myUserId,userId,"fix",xPackets[userId].getAttribute("nr"),"","","0","nragree");
    }
    else
    {
        aMsg = buildEzdiaXmppPacket(aMsg,myUserId,userId,"pm","",xPackets[userId].getAttribute("nr"),"","0","nragree");
    }

    con.send(aMsg);
    var html = "<div class='chatuseragree'>New rate sent to "+fromName+".</div>";
    addInfoToChatWindow(userId, html);

    //Get X
    var xtmp;
    for (var i=0; i<aMsg.getNode().getElementsByTagName('x').length; i++){
        xtmp = aMsg.getNode().getElementsByTagName('x').item(i);
    }

    var billingWinId = userId + "BillingRoot";
    var billingWnd = document.getElementById(billingWinId);
    billingWnd.innerHTML = getRateSentUI(userId, xBillingData[userId].billingSubject, xtmp);
    closecommonconn();
}
function handlePropose_Disagree(userId)
{
    var aMsg = buildJSCACMessage(userId + "@" + con.domain, "ezd");
    aMsg = buildEzdiaXmppPacket(aMsg,myUserId,userId,xPackets[userId].getAttribute("t"),xPackets[userId].getAttribute("fr"),xPackets[userId].getAttribute("vr"),null, 0, "nrdisagree");
    con.send(aMsg);
    var html = "<div class='chatuseragree'>You have disagree for new rate.</div>";
    addInfoToChatWindow(userId, html);
    closecommonconn();
}

//Handle new rates agree by expert 
function handleNewRateAgree(fromName, aJSJaCPacket, x)
{
    var userId = aJSJaCPacket.getFromJID().getNode();
    var html = "<div class='chatuseragree'>" + fromName + " agree to your rate.</div>";
    addInfoToChatWindow(userId, html);

    //Open Billing window and add Rate div to it.
    var billingWinId = aJSJaCPacket.getFromJID().getNode() + "BillingRoot";
    var billingWnd = document.getElementById(billingWinId);
    billingWnd.innerHTML = getRateUI(aJSJaCPacket.getFromJID().getNode(), x, null);
    billingWnd.style.display ='';
}

//Handle new rates disagree by expert.
function handleNewRateDisAgree(fromName, aJSJaCPacket, x)
{
    var userId = aJSJaCPacket.getFromJID().getNode();
    var html = "<div class='chatuseragree'>" + fromName + " disagree to your rate.</div>";
    addInfoToChatWindow(userId, html);

    //Open Billing window and add Rate div to it.
    var billingWinId = aJSJaCPacket.getFromJID().getNode() + "BillingRoot";
    var billingWnd = document.getElementById(billingWinId);
    billingWnd.innerHTML = getRateUI(aJSJaCPacket.getFromJID().getNode(), x, null);
    billingWnd.style.display ='';
}

//Handle start service.
function handleStart(fromName, aJSJaCPacket, x)
{
    var billingWinId = aJSJaCPacket.getFromJID().getNode() + "BillingRoot";
    var billingWnd = document.getElementById(billingWinId);
    billingWnd.innerHTML = getServiceUIForExpert(aJSJaCPacket.getFromJID().getNode(),xPackets[aJSJaCPacket.getFromJID().getNode()],true);
    billingWnd.style.display ='';

    xBillingData[aJSJaCPacket.getFromJID().getNode()].serviceStartTime = new Date();
    xBillingData[aJSJaCPacket.getFromJID().getNode()].lastSyncTime = new Date();
    var html= "<div class='chatuseragree'>" + fromName + " has started the service.</div>";
    addInfoToChatWindow( aJSJaCPacket.getFromJID().getNode(), html);
	
    updateTimer(aJSJaCPacket.getFromJID().getNode());//Start billing timer.
	
}

//Handle stop service. Request can come from both side. 
function handleStop(fromName, aJSJaCPacket, x)
{
    var html= "<div class='chatuseragree'>" + fromName + " has stopped the services.</div>";
    addInfoToChatWindow( aJSJaCPacket.getFromJID().getNode(), html);
    clearTimeout(xBillingData[aJSJaCPacket.getFromJID().getNode()].hndUpdateTimer);

    var hireBtn = document.getElementById(aJSJaCPacket.getFromJID().getNode()+'hireBtn');
    if (hireBtn){
        hireBtn.style.display='block';
    }
    var stopBtn = document.getElementById(aJSJaCPacket.getFromJID().getNode()+'stopBtn');
    if (stopBtn){
        stopBtn.style.display='none';
    }

    var billingWinId = aJSJaCPacket.getFromJID().getNode() + "BillingRoot";
    var billingWnd = document.getElementById(billingWinId);
    ms = parseInt(x.getAttribute("ms"));
    if ((MIN_BILLING_SECONDS*1000) > ms  )// check for minimum time
    {
        ms = MIN_BILLING_SECONDS * 1000;//Set minimum billing seconds.
    }
    if ( x.getAttribute("c") == myUserId) //For explorer.
    {
        if (x.getAttribute("t") == "fix")//Fix rate.
        {
            var totalExp = parseFloat(x.getAttribute("fr"));
            billingWnd.innerHTML = getSummaryInfo(aJSJaCPacket.getFromJID().getNode(),time(ms),totalExp,myBalance - totalExp);
            chatBillingEvent(aJSJaCPacket.getFromJID().getNode(), 1, x.getAttribute("e"), x.getAttribute("fr"), 1);

        }
        else//Rate per min
        {
            ms = roundServiceTime(ms);
            var totalExp = (parseFloat((ms / 1000 /60)) * parseFloat(x.getAttribute("vr") ));
            totalExp = roundNumber(totalExp,2);
            billingWnd.innerHTML = getSummaryInfo(aJSJaCPacket.getFromJID().getNode(),time(ms),totalExp,myBalance - totalExp);
            chatBillingEvent(aJSJaCPacket.getFromJID().getNode(), 1, x.getAttribute("e"), x.getAttribute("vr"), 0);
        }
    }
    else //For Expert.
    {
        if (x.getAttribute("t") == "fix")//Fix rate.
        {
            var totalExp = parseFloat(x.getAttribute("fr"));
            billingWnd.innerHTML = getSummaryInfoForExpert(aJSJaCPacket.getFromJID().getNode(),time(ms),totalExp,myBalance + totalExp);
        }
        else//Rate per min
        {
            ms = roundServiceTime(ms);
            var totalExp = (parseFloat((ms / 1000 /60)) * parseFloat(x.getAttribute("vr") ));
            totalExp = roundNumber(totalExp,2);
            billingWnd.innerHTML = getSummaryInfoForExpert(aJSJaCPacket.getFromJID().getNode(),time(ms),totalExp,myBalance + totalExp);
        }
    }
    billingWnd.style.display ='';
}

//Handle request to pause service. Request can come from both side.
function handleRequestPause(fromName, aJSJaCPacket, x)
{
    var userId = aJSJaCPacket.getFromJID().getNode();
    xBillingData[userId].tmpJSJaCPacket = aJSJaCPacket;
    xBillingData[userId].tmpxPackets = x;
    var html = '<div style="width: 557px; height: auto;">';
    html += '<table id="corner_dialog_table0" align="center" class="corner_dialog_table" style="width: 100%; height: auto;">';
    html += '<tr>';
    html += '<td class="corner_topleft_green"></td>';
    html += '<td class="corner_topborder_green"></td>';
    html += '<td class="corner_topright_grn"></td>';
    html += '</tr>';
    html += '<tr>';
    html += '<td class="corner_borderleft_green"></td>';
    html += '<td id="corner_content_grn0" class="corner_content_grn">';
    html += '<div id="checkoutid"style="width: 100%; height: auto;">';
    html += '<div class="popup-header global-bg-color" style="position:relative; width:539px; margin-left:-10px; margin-top:-10px;">';
    html += '<div style="font-size:14px;">';
    html += 'Pause Service?';
    html += '<div style="cursor: pointer; position: absolute; font-size: 9px; font-weight: bold; right: 10px; width: auto; top: 10px;">';
    //html += '<a href="javascript:void(0);" id="loginpopup_closeimg" onclick="closecommonconn()" style="color: white;">Close X</a>';
    html += '</div>';
    html += '</div>';
    html += '</div>';
    html += '<div id="CashierInnerDiv">';
    html += '<div class="row" style="padding-top:10px;"><div class="cell nml_bluetxt" style="width:300px;text-align:left;">' + fromName + ' has requested to pause. You will not be paid until client resume the service. Are you agree with the request.</div></div>';
    html += '<div class="row" style="padding-top:20px; height:40px;">';
    html += '<div class="cell" style="width:110px; margin-left: 140px;">';
    html += '<a href="javascript:void(0)" class="global-button global-color small-button-padding" onclick="handleRequestPauseAgree(\''+userId+'\')">';
    html += 'Agree';
    html += '</a>';
    html += '</div>';
    html += '<div class="cell" style="width:110px;">';
    html += '<a href="javascript:void(0)" class="global-button global-color small-button-padding" onclick="handleRequestPauseDisagree(\''+userId+'\');">';
    html += 'Disagree';
    html += '</a>';
    html += '</div>';
    html += '</div>';
    html += '</div>';
    html += '</div>';
    html += '</td>';
    html += '<td class="corner_border_right_grn"></td>';
    html += '</tr>';
    html += '<tr>';
    html += '<td class="corner_bottomleft_grn"></td>';
    html += '<td class="corner_border_bottom_grn"></td>';
    html += '<td class="corner_bottomright_grn"></td>';
    html += '</tr>';
    html += '</table>';
    html += '</div>';



    lid = "ConnectionPopUp";

    commoncallback(html, "ConnectionPopUp");

}
function handleRequestPauseAgree(userId)
{
	
    now = new Date();
    xBillingData[userId].totalServiceDurationMs = xBillingData[userId].totalServiceDurationMs + now.getTime() - xBillingData[userId].serviceStartTime.getTime();
    var x = xBillingData[userId].tmpxPackets;
    clearTimeout(xBillingData[userId].hndUpdateTimer);
    var aMsg = buildJSCACMessage(userId + "@" + con.domain, "ezd");
    aMsg = buildEzdiaXmppPacket(aMsg,x.getAttribute("e"),x.getAttribute("c"),x.getAttribute("t"),x.getAttribute("fr"),x.getAttribute("vr"),null,x.getAttribute("n"),"pagree");
    con.send(aMsg);
    document.getElementById(userId+'pause').style.display='none';
    document.getElementById(userId+'resume').style.display='block';
    closecommonconn();
    if (x.getAttribute("c") == myUserId)
    {
        chatBillingEvent(userId, 2, null, null, null);
    }
}
function handleRequestPauseDisagree(userId)
{
    var x = xBillingData[userId].tmpxPackets;
    var aMsg = buildJSCACMessage(userId + "@" + con.domain, "ezd");
    aMsg = buildEzdiaXmppPacket(aMsg,x.getAttribute("e"),x.getAttribute("c"),x.getAttribute("t"),x.getAttribute("fr"),x.getAttribute("vr"),null,x.getAttribute("n"),"pdisagree");
    con.send(aMsg);
    closecommonconn();
}

//Handle pause agree.Request can come from both side.
function handlePauseAgree(fromName, aJSJaCPacket, x)
{
    now = new Date();
    xBillingData[aJSJaCPacket.getFromJID().getNode()].totalServiceDurationMs = xBillingData[aJSJaCPacket.getFromJID().getNode()].totalServiceDurationMs + now.getTime() - xBillingData[aJSJaCPacket.getFromJID().getNode()].serviceStartTime.getTime();
    clearTimeout(xBillingData[aJSJaCPacket.getFromJID().getNode()].hndUpdateTimer);
    var html = "<div class='chatuseragree'>" + fromName + " agree to pause the service.</div>";
    addInfoToChatWindow(aJSJaCPacket.getFromJID().getNode(), html);
    document.getElementById(aJSJaCPacket.getFromJID().getNode()+'pause').style.display='none';
    document.getElementById(aJSJaCPacket.getFromJID().getNode()+'resume').style.display='block';
    if (x.getAttribute("c") == myUserId)
    {
        chatBillingEvent(aJSJaCPacket.getFromJID().getNode(), 2, null, null, null);
    }
}	

//Handle pause disagree.Request can come from both side.
function handlePauseDisagree(fromName, aJSJaCPacket, x)
{
    var html= "<div class='chatuseragree'>" + fromName + " disagree to pause the service.</div>";
    addInfoToChatWindow( aJSJaCPacket.getFromJID().getNode(), html);
}
//Handle pause resume. Request can come from both side.
function handleResumeService(fromName, aJSJaCPacket, x)
{
    xBillingData[aJSJaCPacket.getFromJID().getNode()].hndUpdateTimer = new Date();
    xBillingData[aJSJaCPacket.getFromJID().getNode()].serviceStartTime = new Date();
    xBillingData[aJSJaCPacket.getFromJID().getNode()].lastSyncTime = new Date();
    updateTimer(aJSJaCPacket.getFromJID().getNode());
    var html = "<div class='chatuseragree'>" + fromName + " has resumes the service.</div>";
    addInfoToChatWindow(aJSJaCPacket.getFromJID().getNode(), html);
    document.getElementById(aJSJaCPacket.getFromJID().getNode()+'pause').style.display='block';
    document.getElementById(aJSJaCPacket.getFromJID().getNode()+'resume').style.display='none';
    if (x.getAttribute("c") == myUserId)
    {
        chatBillingEvent(aJSJaCPacket.getFromJID().getNode(), 3, null, null, null);
    }
}

function handlePing(fromName, aJSJaCPacket, x)
{
    if (xBillingData[aJSJaCPacket.getFromJID().getNode()])
    {
        xBillingData[aJSJaCPacket.getFromJID().getNode()].lastSyncTime = new Date();
    }
    var aMsg = buildJSCACMessage(aJSJaCPacket.getFromJID().getNode() + "@" + con.domain, "ezd");
    aMsg = buildEzdiaXmppPacket(aMsg,x.getAttribute("e"),x.getAttribute("c"),x.getAttribute("t"),x.getAttribute("fr"),x.getAttribute("vr"),null,x.getAttribute("n"),"pong");
    con.send(aMsg);
}
function handlePong(fromName, aJSJaCPacket, x)
{
    if (xBillingData[aJSJaCPacket.getFromJID().getNode()])
    {
        xBillingData[aJSJaCPacket.getFromJID().getNode()].lastSyncTime = new Date();
    }
}

//Trim spaces from begning and end of the given string. 
function chattrim(sString)
{
    while (sString.substring(0,1) == ' ' || sString.substring(0,1) == '\n' || sString.substring(0,1) == '\r')
    {
        sString = sString.substring(1, sString.length);
    }
    while (sString.substring(sString.length-1, sString.length) == ' ' )
    {
        sString = sString.substring(0,sString.length-1);
    }
    return sString;
}
function addMessageDeliveryFailureMsg(userId,msg)
{
    var html = '<div class="chatuseragree">'+msg+'</div>';
    var chatBodyDiv = document.getElementById(userId + "chatBody");
    if ( chatBodyDiv )
    {
        chatBodyDiv.innerHTML += html;
        chatBodyDiv.scrollTop = chatBodyDiv.scrollHeight;
    //document.getElementById(userId + "chatBody").lastChild.scrollIntoView(false);
    }
}

//Add message to chat window. Make sure chat window is open before calling this function.
function addMessageToChatWindow(from, userId, msg){
    if (arDhtmlWindows[userId] && arDhtmlWindows[userId].style.display == "none")
    {
        arDhtmlWindows[userId].show(arDhtmlWindows[userId]);
    }
    //showviewprofile("ViewOtherProfile.do?uid=1000000022","middle_div","1000000022","home")
    var html = "";
    msg = chattrim(msg);
    msg = msg.replace(/\r\n/g, '<br />');
    msg = msg.replace(/\n/g, '<br />');
    if (lastMessageSenderName[userId] != from)
    {
        var fromHtml = from;
        if (from != "Me")
        {
            fromHtml = '<a href="javascript:void(0)" onClick="showviewprofile(\'ViewOtherProfile.do?uid='+userId+'\',\'middle_div\',\''+userId+'\',\'home\')">'+from+'</a>';
        }
        html = '<table class="chatuser ' + ((from == "Me")?"username1":"username2") + '"><tr><td width="300"> ' + fromHtml + ' </td><td class="time">' + getCurrentTime() + '</td></tr></table>';
        lastMessageSenderName[userId] = from;
    }
	
    html += '<div class="usertext">' + msg + '</div>';
    //document.getElementById(userId + "Root").style.display='';
    var chatBodyDiv = document.getElementById(userId + "chatBody");
    if ( chatBodyDiv )
    {
        chatBodyDiv.innerHTML += html;
        chatBodyDiv.scrollTop = chatBodyDiv.scrollHeight;
    //document.getElementById(userId + "chatBody").lastChild.scrollIntoView(false);
    }
    if ( from != "Me" && msgBlinkTimer == null && hasWindowFocus == false)
    {
        notifyWindowTitle(from);
    }
    if (from != "Me")
    {
        playSound("chat_recv");//Play sound for chat message
    }
}

//Add information to chat window. 
function addInfoToChatWindow(userId, html){
    var chatBodyDiv = document.getElementById(userId + "chatBody");
    chatBodyDiv.innerHTML += html;
    chatBodyDiv.scrollTop = chatBodyDiv.scrollHeight;
}
function getCurrentTime() // Get current time to add it on Chat UI
{
    var date = new Date();
    var hour = date.getHours();
    var am = false;
    if (hour < 10) {
        hour = '0' + hour;
        am = true;
    } if (hour < 12) {
        am = true;
    }
    var min = date.getMinutes();
    if (min < 10) 
    {
        min = '0' + min;
    }
    return hour + ':' + min + (am ? 'am': 'pm');
}

//Login to chat system.
function doLogin(user,password,httpbasevalue,host) {
    //document.getElementById('err').innerHTML = ''; // reset
    //alert(user+","+password+","+httpbasevalue+","+host);
    if (nextReconnectTimer) // Clear reconnect timer if any
    {
        clearTimeout(nextReconnectTimer);
        nextReconnectTimer = null;
    }
    myUserId = user;
    this.user=user;
    this.password=password;
    this.httpBase = httpbasevalue;
    this.localDomain = host;
    try {
        oDbg = new JSJaCConsoleLogger(2);

        // setup args for contructor
        oArgs = new Object();
        oArgs.httpbase =httpbasevalue;
        oArgs.timerval = 2000;

        if (typeof(oDbg) != 'undefined')
        {
            oArgs.oDbg = oDbg;
        }

        if (backend)
        {
            con = new JSJaCHttpBindingConnection(oArgs);
        }
        else
        {
            con = new JSJaCHttpPollingConnection(oArgs);
        }

        setupCon(con);

        var login_chat = document.getElementById('login_chat');
        if (login_chat)
        {
            login_chat.style.display="none";
        }
        var logout_chat = document.getElementById('logout_chat');
        if (logout_chat)
        {
            logout_chat.style.display="";
        }
      
        var date = new Date();
		
        oArgs = new Object();
        oArgs.domain = host;
        oArgs.username = user;
        oArgs.resource = 'ezdia' + date.getHours() + date.getMinutes()  + date.getSeconds();
        oArgs.pass = password;
        //oArgs.register = aForm.register.checked;
        oArgs.authtype = 'nonsasl';
        con.connect(oArgs);

    } catch (e) {
        document.getElementById('err').innerHTML ='Oops !! There is an error to connect';
    } finally {
        return false;
    }
}
function doReconnect()
{
    if (nextReconnectTimer) // Clear reconnect timer if any
    {
        clearTimeout(nextReconnectTimer);
        nextReconnectTimer = null;
    }
  
    if (!con.connected() && val != 'offline') {
        doLogin(user, password, httpBase, localDomain);
        return;
    }
    var onlstat = 'available';
    var aPresence = new JSJaCPresence();
  
    var val = 'available'; // needed for led in status bar
    aPresence.setStatus('online');    
    aPresence.setShow(val);
    con.send(aPresence);
}
//Handle broadcast messages coming from admin or admin console.
function handleBroadcastMessage(msg){
    alert(msg);
    var gem = document.getElementById('globalErrorMessage');
    if(gem) {
        gem.innerHTML = msg;
    }
}

//Cancel event bubbeling 
function cancelClickBubbeling(e)
{
    if(document.all)
    {
        e = event;
    }
    e.cancelBubble = true;
    if(window.ActiveXObject)    
    {
        event.returnValue = false;    
    }
    else
    {
        e.preventDefault();
    }
}

//Send normal chat message.
function sendMsg(msgBox, e, user) {
    var keycode;
    if (window.event) {
        e  = window.event; keycode = window.event.keyCode;
    }
    else if (e) {
        keycode = e.which;
    }
    else {
        return true;
    }

    var kC  = (window.event) ?  event.keyCode : e.keyCode;// MSIE or Firefox?
    var Esc = (window.event) ?  27 : e.DOM_VK_ESCAPE // MSIE : Firefox
    if(kC==Esc && arDhtmlWindows[user] )
    {
        arDhtmlWindows[user].close();
        cancelEventBubbeling(e);
        return true;
    }


    if ( keycode == 13 )
    {
        if ( e.shiftKey )
        {
            // For IE
            if (document.selection)
            {
                myField.focus();
                sel = document.selection.createRange();
                sel.text = "\r\n";
            }
            else
            {
                var startPos = msgBox.selectionStart;
                var endPos = msgBox.selectionEnd;
                msgBox.value = msgBox.value.substring(0, startPos) + "\r\n" + msgBox.value.substring(endPos, msgBox.value.length);
                msgBox.setSelectionRange(startPos+1, startPos+1);
                msgBox.focus();
            }
            cancelClickBubbeling(e);
        }
        else
        {
            if (chattrim(msgBox.value) == '')
            {
                return;
            }

            try {
                if ( !validateXmppConnection(user) )
                {
                    msgBox.value = '';
                    return;
                }
                addMessageToChatWindow("Me", user, chattrim(msgBox.value));
                var sendTo = user;
                if (sendTo.indexOf('@') == -1) {
                    sendTo += '@' + con.domain;
                }
				
                con.send(buildJSCACMessage(sendTo, chattrim(msgBox.value)));
                msgBox.value = '';

                //if(!checkInChatGroup2(user))
                //	getUserData2('getUserData.do',sendTo,0);

                return;
            } catch (ex) {
                html = '<div class="msg error">Error: Oops there is an error, Try Again </div>';
                document.getElementById(chatBody).innerHTML += html;
                //document.getElementById(chatBody).lastChild.scrollIntoView();
                oDbg.log(html);
                return;
            }
        }
    }
	
}

function loginToChat(button)
{
    if (button)
    {
        button.style.display="none";
    }
    if (!isConnectedToChatServer())
    {
        doReconnect();
    }
	
}

// check Xmpp connection and add error message to user div
function validateXmppConnection(userId)
{
    if (typeof(con) == "undefined" || con.connected() == false) {
        addInfoToChatWindow(userId, '<div class="chatuseragree">Please login to Chat first ! <br /><a style="cursor:pointer;cursor: hand;text-decoration: underline;display:block;" onClick="loginToChat(this)">Login to Chat</a></div>');
        var login_chat = document.getElementById('login_chat');
        if (login_chat)
        {
            login_chat.style.display="";
        }
        var logout_chat = document.getElementById('logout_chat');
        if (logout_chat)
        {
            logout_chat.style.display="none";
        }
		
        //Reconnect to server.
        //doLogin(user,password,httpBase,localDomain);
        return false;
    }
    else
    {
        return true;
    }
}

// Returns xmpp server connected state.
function isConnectedToChatServer()
{
    if (typeof(con) == "undefined" || con.connected() == false) {
        return false;
    }
    else
    {
        return true;
    }
}

//Build JSJaC Message with given jid and message.
function buildJSCACMessage(to,msg)
{
    var aMsg = new JSJaCMessage();
    aMsg.setTo(new JSJaCJID(to));
    aMsg.setType('chat');
    aMsg.setBody(msg);
    return aMsg;
}

function quit() {
    if (con && con.connected()){
        con.disconnect();
        oDbg.log("quit called");
    }
    var login_chat = document.getElementById('login_chat');
    if (login_chat)
    {
        login_chat.style.display="";
    }
    var logout_chat = document.getElementById('logout_chat');
    if (logout_chat)
    {
        logout_chat.style.display="none";
    }
}
/******************Chat Part Ends***************************/

/******************Billing Part Starts**********************/
//Build ezdia billing packet.
/*
aMsg=XMPP Message object
expert=Expert id
customer=customer id
type=rate type
fRate=fixed rate
vRate= rate per min
newRate= new rate
nego= is negotiable
action=actin
*/
function buildEzdiaXmppPacket(aMsg,expert,customer,type,fRate,vRate,newRate,nego,action, totalMS) //Build XMPP Ezdia Billing packet.
{
    var x;
    if(window.ActiveXObject)
    {
        x = aMsg.getNode().appendChild(aMsg.getDoc().createElement('x'));
        x.setAttribute('xmlns','ezdia:xmpp:billing');
    }
    else
    {
        x = aMsg.getNode().appendChild(aMsg.getDoc().createElementNS('ezdia:xmpp:billing','x'));
    }
		 
    x.setAttribute('e',expert);
    x.setAttribute('c',customer);
    if ( type != null )//Type fix/pm
    {
        x.setAttribute('t',type);
    }
    if ( fRate != null )// Rate
    {
        x.setAttribute('fr',fRate);
    }
    if ( vRate != null )// Rate
    {
        x.setAttribute('vr',vRate);
    }
    if ( newRate != null )//New Rate
    {
        x.setAttribute('nr',newRate);
    }
    if ( nego != null ) // Negotiable
    {
        x.setAttribute('n',nego);
    }
    if (totalMS && !isNaN(totalMS))
    {
        x.setAttribute('ms',totalMS);
    }
  
    x.setAttribute('a',action); //Action
    return aMsg;
}

function openRequestUIForHire(expertId)
{
    //Open Billing window and add Rate div to it.
    var billingWinId = expertId + "BillingRoot";
    var billingWnd = document.getElementById(billingWinId);
    billingWnd.innerHTML = getHireRequestUI(expertId);
    billingWnd.style.display ='';
}

function showModelConfirmBox()
{


    var html = "";

    html += '<div style="width: 557px; height: auto;">';
    html += '<table id="corner_dialog_table0" align="center" class="corner_dialog_table" style="width: 100%; height: auto;">';
    html += '<tr>';
    html += '<td class="corner_topleft_green"></td>';
    html += '<td class="corner_topborder_green"></td>';
    html += '<td class="corner_topright_grn"></td>';
    html += '</tr>';
    html += '<tr>';
    html += '<td class="corner_borderleft_green"></td>';
    html += '<td id="corner_content_grn0" class="corner_content_grn">';
    html += '<div id="checkoutid"style="width: 100%; height: auto;">';
    html += '<div class="popup-header global-bg-color" style="position:relative; width:539px; margin-left:-10px; margin-top:-10px;">';
    html += '<div style="font-size:14px;">';
    html += 'Add funds to your account';
    html += '<div style="cursor: pointer; position: absolute; font-size: 9px; font-weight: bold; right: 10px; width: auto; top: 10px;">';
    html += '<a href="javascript:void(0);" id="loginpopup_closeimg" onclick="closecommonconn()" style="color: white;">Close X</a>';
    html += '</div>';
    html += '</div>';
    html += '</div>';
    html += '<div id="CashierInnerDiv">';
    html += '<div class="row" style="padding-top:20px; height:40px;">';
    html += '<div class="cell" style="width:110px; margin-left: 140px;">';
    html += '<a href="javascript:void(0)" class="global-button global-color small-button-padding" onclick="">';
    html += 'Submit Deposit';
    html += '</a>';
    html += '</div>';
    html += '<div class="cell" style="width:110px;">';
    html += '<a href="javascript:void(0)" class="global-button global-color small-button-padding" onclick="closecommonconn();">';
    html += 'Cancel';
    html += '</a>';
    html += '</div>';
    html += '</div>';
    html += '</div>';
    html += '</div>';
    html += '</td>';
    html += '<td class="corner_border_right_grn"></td>';
    html += '</tr>';
    html += '<tr>';
    html += '<td class="corner_bottomleft_grn"></td>';
    html += '<td class="corner_border_bottom_grn"></td>';
    html += '<td class="corner_bottomright_grn"></td>';
    html += '</tr>';
    html += '</table>';
    html += '</div>';



    lid = "ConnectionPopUp";

    commoncallback(html, "ConnectionPopUp");
}

//Send Request for Hire from Explorer to Expert
function requestForHire(expertId)
{
    if ( !validateXmppConnection(expertId) )
    {
        return;
    }
    var subject = document.getElementById(expertId + 'TxtSubject').value;
    if ( subject.length > '50'){
        document.getElementById("BillingErrorMess").style.display = '';
        document.getElementById("BillingErrorMess").innerHTML = 'Subject of topic should be less then 50 Chars';
        document.getElementById(expertId + 'TxtSubject').focus();
        window.setTimeout('cleardiv("BillingErrorMess")',9000);
        return;
    }
    if ( subject != null && subject != "")
    {
        xBillingData[expertId] = new billingData();
        ms = 0;
        xBillingData[expertId].totalServiceDurationMs = 0; //Reset total service time.
        var aMsg = buildJSCACMessage(expertId + "@" + con.domain, subject);
        aMsg = buildEzdiaXmppPacket(aMsg,expertId,myUserId,null,null,null,null,null,"hire");
        var html = "<div class='chatuseragree'>" + getCurrentTime() + "<br>Request sent to hire Expert </div>";
        con.send(aMsg);
        addInfoToChatWindow(expertId, html);
        document.getElementById(expertId+'hireBtn').style.display = 'none';
        document.getElementById("BillingErrorMess").style.display = 'none';
        hideBillingLayer(expertId + 'BillingRoot');

    }
    else
    {
        document.getElementById("BillingErrorMess").style.display = '';
        document.getElementById("BillingErrorMess").innerHTML = 'Please enter subject of the topic.';
        document.getElementById(expertId + 'TxtSubject').focus();
        window.setTimeout('cleardiv("BillingErrorMess")',9000);
        //alert("Please enter subject of the topic.");
        return;
    }
    getUserAccountBalance(expertId);
    showWarningMessageForFunds = true;
}
//Cancel requet for hire.
function cancelHire(userId,infoMsg)
{
    var aMsg = buildJSCACMessage(userId + "@" + con.domain, "ezd");
    aMsg = buildEzdiaXmppPacket(aMsg,myUserId,userId,null,null,null,null,null,"cancel");
    con.send(aMsg);
    infoHtml = "<div class='chatuseragree'>" + getCurrentTime() + "<br>"+infoMsg+"</div>";
    addInfoToChatWindow(userId, infoHtml);

    var hireBtn = document.getElementById(userId+'hireBtn');
    if (hireBtn)// If hire button available then enable it
    {
        hireBtn.style.display = 'block';
    }
    if ( document.getElementById(userId + 'BillingRoot') )
    {
        hideBillingLayer(userId + 'BillingRoot');
    }
    clearUserBalanceChecker();// Clear timer if any
}
// Send price to explorer
function sendRateToExplorer(userId) //Sent by Expert
{
    if ( !validateXmppConnection(userId) )
    {
        return;
    }
    var isAgree = document.getElementById(userId + "ChkTerms").checked;

    if (isAgree == true){
        var priceType;
        var fPrice = "";
        var vPrice = "";
        if ( document.getElementById(userId + 'RatePerMin').checked)
        {
            vPrice = document.getElementById(userId + 'TextRpm').value;
            if (chattrim(vPrice) == "")
            {
                document.getElementById("BillingErrorMess").style.display = '';
                document.getElementById("BillingErrorMess").innerHTML = "Please enter per minute charges.";
                document.getElementById(userId + 'TextRpm').focus();
                window.setTimeout('cleardiv("BillingErrorMess")',9000);
                //alert("Please enter per minute charges.");
                return;
            }
            if (isNaN(vPrice))
            {
                document.getElementById("BillingErrorMess").style.display = '';
                document.getElementById("BillingErrorMess").innerHTML = "Please enter a valid Per/min charges (e.g. 1 or 1.5).";
                document.getElementById(userId + 'TextRpm').focus();
                window.setTimeout('cleardiv("BillingErrorMess")',9000);
                //alert("Please enter a valid Per/min charges (e.g. 1 or 1.5).");
                return;
            }
            if (parseFloat(vPrice) <= 0)
            {
                document.getElementById("BillingErrorMess").style.display = '';
                document.getElementById("BillingErrorMess").innerHTML = "Per minute charges cann't be zero or less";
                document.getElementById(userId + 'TextRpm').focus();
                window.setTimeout('cleardiv("BillingErrorMess")',9000);
                //alert("Per minute charges cann't be zero or less.");
                return;
            }
        }
        if ( document.getElementById(userId + 'RateFix').checked)
        {
            fPrice = document.getElementById(userId + 'TextFix').value;
            if (chattrim(fPrice) == "")
            {
                document.getElementById("BillingErrorMess").style.display = '';
                document.getElementById("BillingErrorMess").innerHTML = "Please enter fix price.";
                document.getElementById(userId + 'TextFix').focus();
                window.setTimeout('cleardiv("BillingErrorMess")',9000);
                //alert("Please enter fix price.");
                return;
            }
            if (isNaN(fPrice))
            {
                document.getElementById("BillingErrorMess").style.display = '';
                document.getElementById("BillingErrorMess").innerHTML = "Please enter a valid fix price (e.g. 1 or 1.5).";
                document.getElementById(userId + 'TextFix').focus();
                window.setTimeout('cleardiv("BillingErrorMess")',9000);
                //alert("Please enter a valid fix price (e.g. 1 or 1.5).");
                return;
            }
            if (parseFloat(fPrice) <= 0)
            {
                document.getElementById("BillingErrorMess").style.display = '';
                document.getElementById("BillingErrorMess").innerHTML = "Fix price cann't be zero or less.";
                document.getElementById(userId + 'TextFix').focus();
                window.setTimeout('cleardiv("BillingErrorMess")',9000);
                //alert("Fix price cann't be zero or less.");
                return;
            }
        }

        if (fPrice == "" && vPrice == "")
        {
            document.getElementById("BillingErrorMess").style.display = '';
            document.getElementById("BillingErrorMess").innerHTML = "Please select price type.";
            window.setTimeout('cleardiv("BillingErrorMess")',9000);
            //alert("Please select price type.");
            return;
        }
        else if (fPrice != "" && vPrice != "")
        {
            priceType = "both";
        }
        else if (fPrice != "" && vPrice == "")
        {
            priceType = "fix";
        }
        else if (fPrice == "" && vPrice != "")
        {
            priceType = "pm";
        }

        var isNego;
        if ( document.getElementById(userId + 'ChkNgo').checked )
        {
            isNego = "1";
        }
        else
        {
            isNego = "0";
        }

        var aMsg = buildJSCACMessage(userId + "@" + con.domain, "ezd");
        aMsg = buildEzdiaXmppPacket(aMsg,myUserId,userId,priceType,fPrice,vPrice,null,isNego,"rate");
        //alert(aMsg.getDoc().xml);
        var html = "<div class='chatuseragree'>" + getCurrentTime() + "<br>Rate sent to explorer.</div>";
        con.send(aMsg);
        addInfoToChatWindow(userId, html);
        //Get X
        var x;
        for (var i=0; i<aMsg.getNode().getElementsByTagName('x').length; i++){
            x = aMsg.getNode().getElementsByTagName('x').item(i);
        }

        var billingWinId = userId + "BillingRoot";
        var billingWnd = document.getElementById(billingWinId);
        billingWnd.innerHTML = getRateSentUI(userId, xBillingData[userId].billingSubject, x);
    }
    else{
        document.getElementById("BillingErrorMess").style.display = '';
        document.getElementById("BillingErrorMess").innerHTML = 'Please agree terms and conditions.';
        document.getElementById(userId+"ChkTerms").focus();
        window.setTimeout('cleardiv("BillingErrorMess")',9000);
    //alert("Please agree terms and conditions.");
    }
}
//Send agree to rate.
function agreeToRate(userId)//Sent by explorer
{
    if ( !validateXmppConnection(userId) )
    {
        return;
    }
    if ( !document.getElementById(userId+"TermsAgree").checked)
    {
        document.getElementById("BillingErrorMess").style.display = '';
        document.getElementById("BillingErrorMess").innerHTML = 'Please agree terms and conditions.';
        document.getElementById(userId+"TermsAgree").focus();
        window.setTimeout('cleardiv("BillingErrorMess")',9000);
        //alert("Please agree terms and conditions.");
        return;
    }
    var rateType = "";
    var rdoRatePerMin = document.getElementById(userId+"RdoPerMin");
    var estimatesServiceMoney =0;
    if ( rdoRatePerMin && rdoRatePerMin.checked )
    {
        rateType = "pm";
        estimatesServiceMoney = parseFloat(xPackets[userId].getAttribute("vr")) * (MIN_BILLING_FUNDS_SECONDS/60);
    }
    else
    {
        rateType = "fix";
        estimatesServiceMoney = parseFloat(xPackets[userId].getAttribute("fr"));
    }
    if (estimatesServiceMoney > myBalance)
    {
        document.getElementById("BillingErrorMess").style.display = '';
        document.getElementById("BillingErrorMess").innerHTML = "You should have funds for at least 5 minutes of talk time";
        window.setTimeout('cleardiv("BillingErrorMess")',9000);
        //alert("You don't have sufficient balance to proceed with this transaction. Please add some funds to proceed.");
        return;
    }
    var aMsg = buildJSCACMessage(userId + "@" + con.domain, "ezd");
    aMsg = buildEzdiaXmppPacket(aMsg,userId,myUserId,rateType,xPackets[userId].getAttribute("fr"),xPackets[userId].getAttribute("vr"),null,xPackets[userId].getAttribute("n"),"agree");
	
    con.send(aMsg);
    var x;
    for (var i=0; i<aMsg.getNode().getElementsByTagName('x').length; i++){
        x = aMsg.getNode().getElementsByTagName('x').item(i);
    }
    xPackets[userId] = x;
    var billingWinId = userId + "BillingRoot";
    var billingWnd = document.getElementById(billingWinId);
    billingWnd.innerHTML = getServiceUI(userId,xPackets[userId]);
    billingWnd.style.display ='';

    if (x.getAttribute("t") == "fix")
    {
        initiateOnAgree(userId, userId, x.getAttribute("fr"), 1);
    }
    else
    {
        initiateOnAgree(userId, userId, x.getAttribute("vr"), 0);
    }
    clearUserBalanceChecker();
}

function sendPing(userId)
{
    var aMsg = buildJSCACMessage(userId + "@" + con.domain, "ezd");
    aMsg = buildEzdiaXmppPacket(aMsg,myUserId,userId,null,null,null,null,null,"ping");
    con.send(aMsg);
}
//Start service.
function startService(userId)
{
    if ( !validateXmppConnection(userId) )
    {
        return;
    }
    var aMsg = buildJSCACMessage(userId + "@" + con.domain, "ezd");
    aMsg = buildEzdiaXmppPacket(aMsg,userId,myUserId,xPackets[userId].getAttribute("t"),xPackets[userId].getAttribute("fr"),xPackets[userId].getAttribute("vr"),null,xPackets[userId].getAttribute("n"),"start");
    con.send(aMsg);

    document.getElementById(userId+'start').style.display='none';
    document.getElementById(userId+'pause').style.display='block';
    document.getElementById(userId+'stopBtn').style.display='block';
    var stopSer = document.getElementById(userId+'stop');
    stopSer.style.display='block';
    document.getElementById(userId+'stopspan').style.color = "#FF0033";
    document.getElementById(userId+'resume').style.display='none';
    xBillingData[userId].serviceStartTime = new Date();
    xBillingData[userId].lastSyncTime = new Date();
	
    updateTimer(userId);
    //Start Service
    chatBillingEvent(userId, 0, null, null, null);
}

//Propose new rate to expert.
function proposeNewRate(userId)
{
    if ( !validateXmppConnection(userId) )
    {
        return;
    }
	

    var rateType = "";
    var rdoRatePerMin = document.getElementById(userId+"RdoPerMin");
    var estimatesServiceMoney =0;
    var newRate = document.getElementById(userId + 'NewRate').value;
    // Validate New Rate
    if (chattrim(newRate) == "")
    {
        document.getElementById("BillingErrorMess").style.display = '';
        document.getElementById("BillingErrorMess").innerHTML = 'Please enter new rate to propose.';
        document.getElementById(userId + 'NewRate').focus();
        window.setTimeout('cleardiv("BillingErrorMess")',9000);
        //alert("Please enter new rate to propose.");
        return;
    }
    if (isNaN(newRate))
    {
        document.getElementById("BillingErrorMess").style.display = '';
        document.getElementById("BillingErrorMess").innerHTML = 'Please enter valid new rate to propose(e.g. 1 or 1.5).';
        document.getElementById(userId + 'NewRate').focus();
        window.setTimeout('cleardiv("BillingErrorMess")',9000);
        //alert("Please enter valid new rate to propose(e.g. 1 or 1.5).");
        return;
    }
    if (parseFloat(newRate) <= 0)
    {
        document.getElementById("BillingErrorMess").style.display = '';
        document.getElementById("BillingErrorMess").innerHTML = "New rate can't be zero or less.";
        document.getElementById(userId + 'NewRate').focus();
        window.setTimeout('cleardiv("BillingErrorMess")',9000);
        //alert("New rate cann't be zero or less.");
        return;
    }
    if ( rdoRatePerMin && rdoRatePerMin.checked )
    {
        rateType = "pm";
        estimatesServiceMoney = parseFloat(newRate) * (MIN_BILLING_FUNDS_SECONDS/60);
    }
    else
    {
        rateType = "fix";
        estimatesServiceMoney = parseFloat(newRate);
    }
    if (estimatesServiceMoney > myBalance)
    {
        document.getElementById("BillingErrorMess").style.display = '';
        document.getElementById("BillingErrorMess").innerHTML = "You don't have sufficient balance to propose this rate. Please add some funds to proceed.";
        window.setTimeout('cleardiv("BillingErrorMess")',9000);
        //alert("You don't have sufficient balance to propose this rate. Please add some funds to proceed.");
        return;
    }
    //if(!confirm("By clicking this, you are going to propose a new rate. Do you want to continue?"))
    //{
    //	return;
    //}
	
    var aMsg = buildJSCACMessage(userId + "@" + con.domain, "ezd");
    aMsg = buildEzdiaXmppPacket(aMsg,userId,myUserId,rateType,xPackets[userId].getAttribute("fr"),xPackets[userId].getAttribute("vr"),newRate,xPackets[userId].getAttribute("n"),"propose");
    con.send(aMsg);
    var html = "<div class='chatuseragree'>New rate sent to hire expert.</div>";
    addInfoToChatWindow(userId, html);
    var BottomButtons = document.getElementById(userId + "BottomButtons" );
    if (BottomButtons)
    {
        BottomButtons.style.display="none";
    }

}

function stopService(userId, force)
{
    if ( ms == 0)
    {
        //Cant stop serice without starting it. Button is disabled.
        return;
    }

    if ( !validateXmppConnection(userId) )
    {
        return;
    }
    if (force == true)
    {
        stopServiceConfirmed(userId, force);
    }
    else
    {
        var html = "";

        html += '<div style="width: 557px; height: auto;">';
        html += '<table id="corner_dialog_table0" align="center" class="corner_dialog_table" style="width: 100%; height: auto;">';
        html += '<tr>';
        html += '<td class="corner_topleft_green"></td>';
        html += '<td class="corner_topborder_green"></td>';
        html += '<td class="corner_topright_grn"></td>';
        html += '</tr>';
        html += '<tr>';
        html += '<td class="corner_borderleft_green"></td>';
        html += '<td id="corner_content_grn0" class="corner_content_grn">';
        html += '<div id="checkoutid"style="width: 100%; height: auto;">';
        html += '<div class="popup-header global-bg-color" style="position:relative; width:539px; margin-left:-10px; margin-top:-10px;">';
        html += '<div style="font-size:14px;">';
        html += 'Stop Service?';
        html += '<div style="cursor: pointer; position: absolute; font-size: 9px; font-weight: bold; right: 10px; width: auto; top: 10px;">';
        //html += '<a href="javascript:void(0);" id="loginpopup_closeimg" onclick="closecommonconn()" style="color: white;">Close X</a>';
        html += '</div>';
        html += '</div>';
        html += '</div>';
        html += '<div id="CashierInnerDiv">';
        html += '<div class="row" style="padding-top:10px;"><div class="cell nml_bluetxt" style="width:220px;">Do you really want to exit the session?</div></div>';
        html += '<div class="row" style="padding-top:20px; height:40px;">';
        html += '<div class="cell" style="width:110px; margin-left: 140px;">';
        html += '<a href="javascript:void(0)" class="global-button global-color small-button-padding" onclick="stopServiceConfirmed(\''+userId+'\', '+((force==true)?true:false)+')">';
        html += 'OK';
        html += '</a>';
        html += '</div>';
        html += '<div class="cell" style="width:110px;">';
        html += '<a href="javascript:void(0)" class="global-button global-color small-button-padding" onclick="closecommonconn();">';
        html += 'Cancel';
        html += '</a>';
        html += '</div>';
        html += '</div>';
        html += '</div>';
        html += '</div>';
        html += '</td>';
        html += '<td class="corner_border_right_grn"></td>';
        html += '</tr>';
        html += '<tr>';
        html += '<td class="corner_bottomleft_grn"></td>';
        html += '<td class="corner_border_bottom_grn"></td>';
        html += '<td class="corner_bottomright_grn"></td>';
        html += '</tr>';
        html += '</table>';
        html += '</div>';



        lid = "ConnectionPopUp";

        commoncallback(html, "ConnectionPopUp");
    }
}

//Stop service.
function stopServiceConfirmed(userId, force)
{
    if (force == false)
    {
        closecommonconn();
    }
    clearTimeout(xBillingData[userId].hndUpdateTimer);
    var hireBtn = document.getElementById(userId+'hireBtn');
    if (hireBtn){
        hireBtn.style.display='block';
    }
    //document.getElementById(userId+'start').style.display='none';
    //document.getElementById(userId+'pause').style.display='none';
    //document.getElementById(userId+'resume').style.display='none';
    var stopBtn = document.getElementById(userId+'stopBtn')
    if (stopBtn){
        stopBtn.style.display='none';
    }
    var aMsg = buildJSCACMessage(userId + "@" + con.domain, "ezd");

    if ((MIN_BILLING_SECONDS*1000) > ms  )// check for minimum time
    {
        ms = MIN_BILLING_SECONDS * 1000;
    }
    aMsg = buildEzdiaXmppPacket(aMsg,xPackets[userId].getAttribute("e"),xPackets[userId].getAttribute("c"),xPackets[userId].getAttribute("t"),xPackets[userId].getAttribute("fr"),xPackets[userId].getAttribute("vr"),null,xPackets[userId].getAttribute("n"),"stop", ms);
    con.send(aMsg);
	
    var billingWinId = userId + "BillingRoot";
    var billingWnd = document.getElementById(billingWinId);
	
    if ( xPackets[userId].getAttribute("c") == myUserId)// From Explorer
    {
        if (xPackets[userId].getAttribute("t") == "fix")
        {
            var totalExp = parseFloat(xPackets[userId].getAttribute("fr"));
            billingWnd.innerHTML = getSummaryInfo(userId,time(ms),totalExp,myBalance - totalExp);
            chatBillingEvent(userId, 1, xPackets[userId].getAttribute("e"), xPackets[userId].getAttribute("fr"), 1);
        }
        else
        {
            ms = roundServiceTime(ms);
            var totalExp = (parseFloat((ms / 1000 /60)) * parseFloat(xPackets[userId].getAttribute("vr") ));
            totalExp = roundNumber(totalExp,2);
            billingWnd.innerHTML = getSummaryInfo(userId,time(ms),totalExp,myBalance - totalExp);
            chatBillingEvent(userId, 1, xPackets[userId].getAttribute("e"), xPackets[userId].getAttribute("vr"), 0);
        }
    }
    else//From Expert
    {
        if (xPackets[userId].getAttribute("t") == "fix")
        {
            var totalExp = parseFloat(xPackets[userId].getAttribute("fr"));
            billingWnd.innerHTML = getSummaryInfoForExpert(userId,time(ms),totalExp,myBalance + totalExp);
        }
        else
        {
            ms = roundServiceTime(ms);
            var totalExp = (parseFloat((ms / 1000 /60)) * parseFloat(xPackets[userId].getAttribute("vr") ));
            totalExp = roundNumber(totalExp,2);
            billingWnd.innerHTML = getSummaryInfoForExpert(userId,time(ms),totalExp,myBalance + totalExp);
        }
		
    }
    billingWnd.style.display ='';
	
}

function roundServiceTime(msToRound)
{
    var serviceMin = msToRound / 1000 / 60;
    var serviceMin = Math.round(serviceMin);
    return serviceMin * 1000 * 60;
}

//Send requet to pause the service.
function requestPauseService(userId)
{
    if ( !validateXmppConnection(userId) )
    {
        return;
    }
    var aMsg = buildJSCACMessage(userId + "@" + con.domain, "ezd");
    aMsg = buildEzdiaXmppPacket(aMsg,xPackets[userId].getAttribute("e"),xPackets[userId].getAttribute("c"),xPackets[userId].getAttribute("t"),xPackets[userId].getAttribute("fr"),xPackets[userId].getAttribute("vr"),null,xPackets[userId].getAttribute("n"),"rpause");
    con.send(aMsg);
    var html = "<div class='chatuseragree'>Requested to pause the service.</div>";

    addInfoToChatWindow(userId, html);
}

//Resume paused service.
function resumeService(userId)
{	
    if ( !validateXmppConnection(userId) )
    {
        return;
    }
    xBillingData[userId].lastSyncTime = new Date();
    xBillingData[userId].serviceStartTime = new Date();
    updateTimer(userId);
    var aMsg = buildJSCACMessage(userId + "@" + con.domain, "ezd");
    aMsg = buildEzdiaXmppPacket(aMsg,xPackets[userId].getAttribute("e"),xPackets[userId].getAttribute("c"),xPackets[userId].getAttribute("t"),xPackets[userId].getAttribute("fr"),xPackets[userId].getAttribute("vr"),null,xPackets[userId].getAttribute("n"),"resume");
    con.send(aMsg);
    document.getElementById(userId+'pause').style.display='block';
    document.getElementById(userId+'resume').style.display='none';
    if (xPackets[userId].getAttribute("c") == myUserId)
    {
        chatBillingEvent(userId, 3, null, null, null);
    }
}

function stopServiceOnError(userId)
{
    stopService(userId, true);
}
// Update time for service
function updateTimer(userId)
{
    xBillingData[userId].hndUpdateTimer = setTimeout("updateTimer('"+userId+"');", 1000);

    now = new Date();
    ms = xBillingData[userId].totalServiceDurationMs + (now.getTime() - xBillingData[userId].serviceStartTime.getTime());
    document.getElementById(userId+'TimerId').innerHTML=time(ms);
    var syncDiff = (new Date()) - xBillingData[userId].lastSyncTime;
    if ( xPackets[userId].getAttribute("t") != "fix" && xPackets[userId].getAttribute("e") == myUserId) //Update Price at Expert Side.
    {
        if ( ((ms/1000)%30) <= 1) //Update rate every 30 second
        {
            xBillingData[userId].earnedMoney = (parseFloat((ms / 1000 /60)) * parseFloat(xPackets[userId].getAttribute("vr") ));
            xBillingData[userId].earnedMoney = roundNumber(xBillingData[userId].earnedMoney,2);
            xBillingData[userId].earnedMoneyEzdia = xBillingData[userId].earnedMoney * 5 / 100;
            document.getElementById(userId+'Earned').innerHTML = xBillingData[userId].earnedMoney + ' $';
            //document.getElementById(userId+'EarnedEzdia').innerHTML = earnedMoneyEzdia + ' $';
			
            if (syncDiff > 35000)//Stop service is no connectivity for more then 35 seconds.
            {
                stopServiceOnError(userId, true);
                alert("Service has to stop because connectivity lost with Explorer.");
            }
            sendPing(userId); // send Ping from expert side only after every 30 secodns.
        }
    }
    if ( xPackets[userId].getAttribute("t") == "fix" && xPackets[userId].getAttribute("e") == myUserId) //Update Fix Price at Expert Side.
    {
        document.getElementById(userId+'Earned').innerHTML = xPackets[userId].getAttribute("fr") + ' $';
    }
    else//Update Time and Money remaining at explorer side
    {
		

        if ( ((ms/1000)%30) <= 1) //Update java server status every 30 seconds
        {
            chatBillingEvent(userId, 5, null, null, null);
            if (xPackets[userId].getAttribute("t") == "pm")
            {
                var totalExp = (parseFloat((ms / 1000 /60)) * parseFloat(xPackets[userId].getAttribute("vr") ));
                totalExp = roundNumber(totalExp,2);
                timeAvailable = document.getElementById(userId + "timeAvailable");
                timeAvailable.innerHTML = roundNumber((myBalance - totalExp) / parseFloat(xPackets[userId].getAttribute("vr") ),2 ) + ":00";
                var totalExpWithOneMin = parseFloat(xPackets[userId].getAttribute("vr")) + totalExp;
                if (totalExpWithOneMin > myBalance)//If funds are not sufficient for next minuts then stop the service.
                {
                    stopService(userId, true);
                    document.getElementById("BillingErrorMess").style.display = '';
                    document.getElementById("BillingErrorMess").innerHTML = "Service has to stop because of you don't have sufficient funds.";
                    window.setTimeout('cleardiv("BillingErrorMess")',9000);
                //alert("Service has to stop because of you don't have sufficient funds.");
                }
                if (syncDiff > 35000)//Stop service is no connectivity for more then 35 seconds.
                {
                    stopServiceOnError(userId, true);
                    document.getElementById("BillingErrorMess").style.display = '';
                    document.getElementById("BillingErrorMess").innerHTML = "Service has to stop because connectivity lost with Expert.";
                    window.setTimeout('cleardiv("BillingErrorMess")',9000);
                //alert("Service has to stop because connectivity lost with Expert.");
                }
            //var totalExpWithWarningMin = parseFloat(xPacket.getAttribute("vr")*(FUNDS_WARNING_SECONDS/60)) + totalExp;
            //if (totalExpWithWarningMin > myBalance && showWarningMessageForFunds == true)//If funds are not sufficient for totalExpWithWarningMin seconds then warn user to add funds.
            //{
            //	setTimeout("showFundsWarningMessage()",0);//Don't block current js timer to show alert.
            //}
            }
        }
		
    }
}

function showFundsWarningMessage()
{
    showWarningMessageForFunds = false;
    alert("Service will be stopped soon because of low funds. Please add enough funds to your account to continue uninterrupted  service.");
}
//Pad string with 2
function two(x) { //Gariam: Make digit in XX format
    return ((x>9)?"":"0")+x;
}
// Pad string with 3
function three(x) {
    return ((x>99)?"":"0")+((x>9)?"":"0")+x;
}

// Convert milliseconds to time
function time(ms) {
    var sec = Math.floor(ms/1000);
    ms = ms % 1000;
    t = three(ms);

    var min = Math.floor(sec/60);
    sec = sec % 60;
    //t = two(sec) + ":" + t;
    t = two(sec);

    var hr = Math.floor(min/60);
    min = min % 60;
    t = two(min) + ":" + t;

    var day = Math.floor(hr/60);
    hr = hr % 60;
    t = two(hr) + ":" + t;
    //t = day + ":" + t;

    return t;
}

function unhideBillingLayer(userId, button)
{
    var winBillingRoot = document.getElementById(userId + "BillingRoot");
    if (winBillingRoot)
    {
        winBillingRoot.style.display ='';
    }
    if (button)
    {
        button.style.display ='none';
    }
}
//Hire billing layer from chat window.
function hideBillingLayer(leftDragDiv,user,hirebtn)
{
    var ele_visibibility = document.getElementById(leftDragDiv).style.display;
    if(ele_visibibility != "none")
    {
        document.getElementById(leftDragDiv).style.display ='none';
        var unHideButton = document.getElementById("openSlideWin"+user);
        if (user && unHideButton)
        {
            unHideButton.style.display = "";
        }
        return true;
    }

    return false;
}

/******************Billing Part Ends************************/
/******************UI Code Start*************************/
function updateLoingLogoutLinks()
{
    try
    {
        if ( isConnectedToChatServer() )
        {
            var login_chat = document.getElementById('login_chat');
            if (login_chat)
            {
                login_chat.style.display="none";
            }
            var logout_chat = document.getElementById('logout_chat');
            if (logout_chat)
            {
                logout_chat.style.display="";
            }
        }
        else
        {
            var login_chat = document.getElementById('login_chat');
            if (login_chat)
            {
                login_chat.style.display="";
            }
            var logout_chat = document.getElementById('logout_chat');
            if (logout_chat)
            {
                logout_chat.style.display="none";
            }
        }
		
    }
    catch (e)
    {
    }
}

//If service is going on then don't allow user to close the chat window.
function beforeClose(userId) // Area to perform some action before closing the window. 
{
    if ( document.getElementById(userId+"stop") )
    {
        alert("Please stop the service before you close this window.");
        return false;
    }
}

function allowMultipleHire()
{
    if (MIN_BILLING_ALLOW_MULTIPLE_SERVE)
    {
        return true;
    }
    for(var tmpService in xBillingData)
    {
        if (document.getElementById(tmpService+"stop"))
        {
            return false;
        }
    }
    return true;
}
//Update document height and width to limit the chat window scrolling.
function updateWindowHeightWidth()
{
    //opera Netscape 6 Netscape 4x Mozilla
    if (window.innerWidth || window.innerHeight){
        documentWidth = window.innerWidth;
        documentHeight = window.innerHeight;
    }
    //IE Mozilla
    if (document.body.clientWidth || document.body.clientHeight){
        documentWidth = document.body.clientWidth;
        documentHeight = document.body.clientHeight;
    }
    documentHeight = Math.max(
        document.documentElement.clientWidth,
        document.body.scrollWidth,
        document.documentElement.scrollWidth,
        document.body.offsetWidth,
        document.documentElement.offsetWidth);
//	var D = document;
//	documentHeight = Math.max(
//        Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
//        Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
//        Math.max(D.body.clientHeight, D.documentElement.clientHeight)
//    );
	
}
//Stop message notification if runing
window.onfocus = function () {
    hasWindowFocus = true;
    if ( msgBlinkTimer != null )
    {
        clearTimeout(msgBlinkTimer);
        document.title = lastWindowTitle;
        msgBlinkTimer = null;
    }
    window.title = lastWindowTitle;
}
window.onblur = function () {

    hasWindowFocus = false;
}

// Blink window title for new messages.
function notifyWindowTitle(msgSenderName)
{
    var notifyMsg = msgSenderName + " Says...";
    if ( document.title != notifyMsg )
    {
        lastWindowTitle = document.title;
    }


    if ( lastWindowTitle == document.title)
    {
        document.title = msgSenderName + " Says...";
        window.focus();
    }
    else
    {
        document.title = lastWindowTitle;
    }
    msgBlinkTimer = setTimeout("notifyWindowTitle('"+msgSenderName+"');", 1500);
}

//get Rate UI
function getBillingRequestUI(userId, subject)
{
    var hire = userId + 'BillingRoot';
    var rateSession = userId + 'rateSession';
    var availableBalanceSpan = userId + 'availableBalance';
    var checkBox = userId + 'checkBox';
    var checkBoxRatePerMin = userId + 'RatePerMin';
    var checkBoxRateFix = userId + 'RateFix';
    var checkBoxError = userId + 'checkBoxError';
    var categoryCombo = userId + 'Category';
	
    var html ='<div class="ChatBilling_header_nav">';
    html+='<table align="right" width="340" cellpadding="0" cellspacing="0"><tr><td width="5"><img src="'+PRESENCE_SERVICE_URL.replace('$uid$',userId)+ '&rnd=' + Math.random()+'" /></td><td class="topUserName" width="300">Billing</td><td><table align="center" width="12"><tr><td><img onclick="hideBillingLayer(\''+hire+'\', \''+userId+'\')" alt="" src="../static/images/chatBillingSideArrowImg.png" style="cursor: pointer; padding-right: 7px;"/></td></tr></table></td></tr></table>';
    html+='</div>';
    //End Billing div Header

    //start Rates div
    html+='<div class="base_bg_holder">';
    html+='<div class="ChatBilling_sendRate_txt">Send Rate for this session</div>';
    html+='<div id="BillingErrorMess" class="msgYellow chatErrorDisplay" style="display:none;"></div>';
    html+= '<div style="color:#76AE31; padding: 4px 0px 2px 10px;">'+subject+'</div>';
    html+= '<div style="float:left; padding:2px;">Select the category for above subject:</div>';
    html+='<div style="float:left;"><select style="width:140px;" size="1" id="'+categoryCombo+'" onchange="document.getElementById(\''+userId+'TextRpm\').value=this.value;"></select></div>';
	
    //Per Min Rate
    html+='<div class="row" style="width:290px;"><div class="cell" style="width:14px;"><input type="checkbox" id="'+checkBoxRatePerMin+'"></div><div class="cell" style="margin-top:8px; width:99px;">Per minute charges :</div>';
    html+='<div class="cell" style="margin-left:0; width:50px;"><input type="text" size="5" id="'+userId + 'TextRpm' +'"></div><div class="cell" style="margin-top:8px; margin-left:0; width:50px; color:#CCC;">$ per min</div></div>';
	
    // Fix Rate
    html+='<div class="row" style="width:290px; height:auto;"><div class="cell" style="width:14px;"><input type="checkbox" id="'+checkBoxRateFix+'"></div><div class="cell" style="margin-top:8px; width:47px;">Fix Price :</div>';
    html +='<div class="cell" style="margin-left:0; width:50px;"><input type="text" size="5" id="'+userId + 'TextFix' +'"></div><div class="cell" style="margin-top:8px; width:50px; color:#CCC;">$ per talk</div></div>';
	
    // Negotiable
    html+='<div class="row" style="margin:0; border-top:1px solid #E5E5E5;">';
    html+='<div class="row" style="width:290px;">';
    html+='<div class="cell" style="width:14px; margin-top:0;"><input type="checkbox" id="'+userId + 'ChkNgo' +'"></div><div class="cell" style="width:110px; color:#004080; margin-top:3px;">My Rate is Negotiable</div></div>';
    
    html+='<div class="row" style="color: rgb(0, 64, 128); width: 290px;"><div class="cell" style="width:14px; margin-top:0;"><input type="checkbox" id="'+userId + 'ChkTerms' +'"></div>';
    html+='<div class="cell" style="width:260px; color:#004080; margin-top:3px;">I Agree to the Expert Fee <span class="action" style="text-decoration:underline;" onclick="myPopUp(\''+contextRoot+'/jsp/TermsAndConditions.jsp\')">Agreement</span> for all the transactions made</div>';
    html+='</div></div>';

    html+='<div class="row" style="width: 200px; padding-top: 0px; margin-left: 90px;">';
    html+='<div class="cell chat-billing-small-Btn"><span class="action" onclick=sendRateToExplorer("'+userId+'")>Send</span></div>';
    html+='<div class="cell chat-billing-small-Btn"><span class="action" onclick="cancelHire(\''+userId+'\',\'You have cancelled the request to hire.\')" >Cancel</span></div></div></div>';

	
    return html;
//End Rate Session div
}

//Get rate send ui
function getRateSentUI(userId, subject, x)
{
    var html ='<div class="ChatBilling_header_nav">';
    html+='<table align="right" width="340" cellpadding="0" cellspacing="0"><tr><td width="5"><img src="'+PRESENCE_SERVICE_URL.replace('$uid$',userId)+ '&rnd=' + Math.random()+'" /></td><td class="topUserName" width="300">Billing</td><td><table align="center" width="12"><tr><td>&nbsp;</td></tr></table></td></tr></table>';
    html +='</div>';

    html += '<div class="base_bg_holder">' +
    '<div class="ChatBilling_sendRate_txt">Send Rate for this session</div>';

    html += '<div style="height:auto; margin: 4px 0px; -moz-border-radius:6px; background-color:#DAEFFE;">' +
    '<div style="padding: 5px 10px;">Subject: <span style="color:#76AE31">'+subject+'</span></div>';
        
    if (x.getAttribute("t") == "pm" || x.getAttribute("t") == "both")
    {
        html += '<div style="padding: 5px 22px;">Per minute charges : '+
        '<span style="color:#004080;">'+x.getAttribute("vr")+'&nbsp; $ per min</span></div>';
    }
    if (x.getAttribute("t") == "fix" || x.getAttribute("t") == "both")
    {
        html += '<div style="padding: 5px 22px;">Fix Price : ' +
        '<span style="color:#004080;">'+x.getAttribute("fr")+'&nbsp; $</span></div>';
    }
    
    if (x.getAttribute("n") == "1")
    {
        html +='<div style="padding: 15px; color:#FF0033;">* You have given a chance to negotiate rate.</div>';
    }
    html +='</div>';
    html +='<div style="border-top:1px solid #E5E5E5;">';
    html +='<div class="chat-billing-small-Btn" style="margin: 15px 140px;"><span class="action" onclick="cancelHire(\''+userId+'\',\'You have cancelled the request to hire.\')">Cancel</span></div></div></div>';
    return html;
}

//Get UI to make a request for hire.
function getHireRequestUI(userId)
{
    var hireSubject = userId + 'TxtSubject';
    var hire = userId + 'BillingRoot';
    var html ='<div class="ChatBilling_header_nav">';
    html+='<table align="right" width="340" cellpadding="0" cellspacing="0"><tr><td width="5"><img src="'+PRESENCE_SERVICE_URL.replace('$uid$',userId)+ '&rnd=' + Math.random()+'" /></td><td class="topUserName" width="300">Hire</td><td><table align="center" width="12"><tr><td><img onclick="hideBillingLayer(\''+hire+'\', \''+userId+'\')" alt="" src="../static/images/chatBillingSideArrowImg.png" style="cursor: pointer; padding-right: 7px;"/></td></tr></table></td></tr></table>';
    html+='</div>';
    //End Billing div Header

    //start Rates div
    html+='<div class="base_bg_holder">';
    html+='<div id="BillingErrorMess" class="msgYellow chatErrorDisplay" style="display:none;"></div>';
    html+='<div class="ChatBilling_title_txt">Please enter the subject of the topic & click Hire</div>';
    html+='<div style="padding:10px 2px 2px 10px;"><input type="text" style="width:300px" id="'+hireSubject+'"/></div>';
	
    html+='<div class="row" style="margin-left: 100px; width: 228px;">';
    html+='<div class="cell chat-billing-small-Btn"><span class="action" onclick=requestForHire("'+userId+'")>Hire</span></div>';
    html+='<div class="cell chat-billing-small-Btn"><span class="action" onclick="hideBillingLayer(\''+userId + 'BillingRoot\');" >Cancel</span></div></div><br/><br/><p align="center"><font color="#CCC">Note: The subject of the topic should be less then 50 Chars.</font></p></div>';

	
    return html;
}

//Get UI to make a request for hire.
function getIncomingHireRequestUI(userId, msg)
{	
    var hire = userId + 'BillingRoot';
    var html ='<div class="ChatBilling_header_nav">';
    html+='<table align="right" width="340" cellpadding="0" cellspacing="0"><tr><td width="5"><img src="'+PRESENCE_SERVICE_URL.replace('$uid$',userId)+ '&rnd=' + Math.random()+'" /></td><td class="topUserName" width="300">Hire Request</td><td><table align="center" width="12"><tr><td><img onclick="hideBillingLayer(\''+hire+'\', \''+userId+'\')" alt="" src="../static/images/chatBillingSideArrowImg.png" style="cursor: pointer; padding-right: 7px;"/></td></tr></table></td></tr></table>';
    html+='</div>';
    //End Billing div Header

    //start Rates div
    html+='<div class="base_bg_holder">';
    html+='<div class="ChatBilling_title_txt" style="padding-top:10px;">'+msg+'</div>';
	
    html+='<div class="row" style="margin-left: 100px; width: 228px;">';
    html+='<div class="cell chat-billing-small-Btn"><span class="action" onclick=agreeForHireRequest("'+userId+'")>Agree</span></div>';
    html+='<div class="cell chat-billing-small-Btn"><span class="action" onclick="cancelHire(\''+userId + '\', \'You have Cancelled the request for hire.\');" >Cancel</span></div></div></div>';

	
    return html;
}

//Get UI for incoming rate for explorer.
function getRateUI(userId, x, currSelectedRateType)
{
    var hire = userId + 'BillingRoot';
    var rateSession = userId + 'rateSession';
    var availableBalanceSpan = userId + 'availableBalance';
    var checkBox = userId + 'checkBox';
    var checkBoxError = userId + 'checkBoxError';
    var avalBal = userId + 'AvalBalance';
    if (currSelectedRateType == null)
    {
        if ( x.getAttribute("t") == "fix")
            currSelectedRateType = "fix";
        else
            currSelectedRateType = "pm";
    }
	
    var html ='<div class="ChatBilling_header_nav">';
    html+='<table align="right" width="340" cellpadding="0" cellspacing="0"><tr><td width="5"><img src="'+PRESENCE_SERVICE_URL.replace('$uid$',userId)+ '&rnd=' + Math.random()+'" /></td><td class="topUserName" width="300">Billing</td><td><table align="center" width="12"><tr><td>&nbsp;</td></tr></table></td></tr></table>';
    html+='</div>';

    html +='<div class="base_bg_holder">';
    html +='<div id="BillingErrorMess" class="msgYellow chatErrorDisplay chatErrorDisplay" style="display:none;"></div>';
    html +='<div class="row thd">';
    html +='<div class="cell" style="width:92px; padding-left:8px;">Available Balance :</div>';
    html +='<div class="cell" style="width:105px;" id="'+avalBal+'"> '+myBalance+'$</div>';
    html +='<div class="cell afl" onClick="showcommondiv(\'AddFund.do\', \'ConnectionPopUp\',\'ConnectionPopUp\');currentWinRemoteUserId='+userId+';">Add funds</div></div>';
    html +='<div class="ChatBilling_sendRate_txt">Rate for this session</div>';
    html +='<div class="bdr-color-E5E5E5">';

    var rateInfoMsg = "";
    if ( x.getAttribute("t") == "pm" || x.getAttribute("t") == "both")
    {
        html += '<div class="row" style="height:20px;">' +
        '<div class="cell" style="margin: 1px; width: 20px;">'+
        '<input type="radio" name="'+userId+'rdoName" id="'+userId+'RdoPerMin" '+((currSelectedRateType=="pm")?'checked="checked"':'')+' onclick="updateRateInfo(\''+userId+'RateInfo\',\'Expert Rate /Min\',\''+x.getAttribute("vr")+'\');" ></div>' +
        '<div class="cell" style="width:200px;">Per minute charges : ' +
        '<span style="color:#004080;">'+x.getAttribute("vr")+'&nbsp; $ per min</span></div></div>';
        rateInfoMsg = '<span>Expert Rate /Min :</span>&nbsp;<span style="color:#004080;">'+x.getAttribute("vr")+' $</span>';
    }
    if ( x.getAttribute("t") == "fix" || x.getAttribute("t") == "both")
    {
        html += '<div class="row" style="height:20px;">' +
        '<div class="cell" style="margin: 1px; width: 20px;">'+
        '<input type="radio" name="'+userId+'rdoName" id="'+userId+'RdoFix" '+((currSelectedRateType!="pm")?'checked="checked"':'')+' onclick="updateRateInfo(\''+userId+'RateInfo\',\'Fix Price\',\''+x.getAttribute("fr")+'\');"></div>' +
        '<div class="cell">Fix Price : ' +
        '<span style="color:#004080;">'+x.getAttribute("fr")+'&nbsp; $</span></div></div>';
        if (currSelectedRateType == "fix")
        {
            rateInfoMsg = '<span>Fix Price :</span>&nbsp;<span style="color:#004080;">'+x.getAttribute("fr")+' $</span>';
        }
		
    }
    if ( x.getAttribute("n") == "1")// Provide option for negotiation.
    {
        html += '<div class="row nR">' +
        '<div class="cell" style="width:14px; margin-top:0;"><input type="checkbox" onclick="updateRateUI(this,\''+userId+'\');"></div>' +
        '<div class="cell" style="width:160px; margin-top:3px;">Negotiate Rate ( only one time  )</div></div>';
    }
    html += '</div>';
    html += '<div class="rimd"><br>' +
    '<div align="center" class="rI" id="'+userId+'RateInfo">'+rateInfoMsg+'</div>' +
    '<div class="row">' +
    '<div class="cell" style="width:15px; margin-top:0;"><input type="checkbox" id="'+userId+'TermsAgree"></div>' +
    '<div class="cell" style="width:291px; margin-top:1px;">I Agree to the Expert Fee <span class="action" style="text-decoration:underline;" onclick="myPopUp(\''+contextRoot+'/jsp/TermsAndConditions.jsp\')">Agreement</span> for all the transactions made.</div></div>' +
    '<div class="row" style="width: 200px; margin-left: 90px;">' +
    '<div class="cell chat-billing-small-Btn"><span class="action" style="color:#76AE31;" onclick=agreeToRate("'+userId+'") >Agree</span></div>' +
    '<div class="cell chat-billing-small-Btn"><span class="action" onclick="cancelHireButtonClicked(\'By clicking this, you are going to cancel the rate proposed by Expert. Click OK to continue.\', \''+userId+'\',\'You have canceled the rate sent from Expert. You may indicate your interest over chat and hire him again by clicking on the Hire button.\')">Cancel</span></div></div></div></div>';
	 


    //html+='</div>';
    return html;
//End Rate Session div
}

//Get Rate UI with negotiable option.
function getRateUIWithNego(userId, x, currSelectedRateType)
{
    var hire = userId + 'BillingRoot';
    var rateSession = userId + 'rateSession';
    var availableBalanceSpan = userId + 'availableBalance';
    var checkBox = userId + 'checkBox';
    var checkBoxError = userId + 'checkBoxError';
    var avalBal = userId + 'AvalBalance';

    var html ='<div class="ChatBilling_header_nav">';
    html+='<table align="right" width="340" cellpadding="0" cellspacing="0"><tr><td width="5"><img src="'+PRESENCE_SERVICE_URL.replace('$uid$',userId)+ '&rnd=' + Math.random()+'" /></td><td class="topUserName" width="300">Billing</td><td><table align="center" width="12"><tr><td>&nbsp;</td></tr></table></td></tr></table>';
    html+='</div>';

    html +='<div class="base_bg_holder">';
    html+='<div id="BillingErrorMess" class="msgYellow chatErrorDisplay" style="display:none;"></div>';
    html +='<div class="row thd">';
    html +='<div class="cell" style="width:92px; padding-left:8px;">Available Balance :</div>';
    html +='<div class="cell" style="width:105px;" id="'+avalBal+'"> '+myBalance+'$</div>';
    html +='<div class="cell afl" onClick="showcommondiv(\'AddFund.do\', \'ConnectionPopUp\',\'ConnectionPopUp\');currentWinRemoteUserId='+userId+';">Add funds</div></div>';
    html +='<div class="ChatBilling_sendRate_txt" style="color:#004080;">Rate for this session</div>';
    html +='<div class="bdr-color-E5E5E5">';

    var rateInfoMsg = "";
    if ( x.getAttribute("t") == "pm" || x.getAttribute("t") == "both")
    {
        html += '<div class="row">' +
        '<div class="cell" style="margin: 1px; width: 20px;">'+
        '<input type="radio" name="'+userId+'rdoName" id="'+userId+'RdoPerMin" '+((currSelectedRateType=="pm")?'checked="checked"':'')+'  onclick="updateRateInfo(\''+userId+'RateInfo\',\'Expert Rate /Min\',\''+x.getAttribute("vr")+'\');" ></div>' +
        '<div class="cell" style="width:200px;">Per minute charges : ' +
        '<span style="color:#004080;">'+x.getAttribute("vr")+'&nbsp; $ per min</span></div></div>';
        rateInfoMsg = '<span>Expert Rate /Min :</span>&nbsp;<span style="color:#004080;">'+x.getAttribute("vr")+' $</span>';
    }
    if ( x.getAttribute("t") == "fix" || x.getAttribute("t") == "both")
    {
        html += '<div class="row">' +
        '<div class="cell" style="margin: 1px; width: 20px;">'+
        '<input type="radio" name="'+userId+'rdoName" id="'+userId+'RdoFix" '+((currSelectedRateType!="pm")?'checked="checked"':'')+' onclick="updateRateInfo(\''+userId+'RateInfo\',\'Fix Price\',\''+x.getAttribute("fr")+'\');"></div>' +
        '<div class="cell">Fix Price : ' +
        '<span style="color:#004080;">'+x.getAttribute("fr")+'&nbsp; $</span></div></div>';
        if (currSelectedRateType!="pm")
        {
            rateInfoMsg = '<span>Fix Price :</span>&nbsp;<span style="color:#004080;">'+x.getAttribute("fr")+' $</span>';
        }
    }
    if ( x.getAttribute("n") == "1")// Provide option for negotiation.
    {
        html += '<div class="row nR">' +
        '<div class="cell" style="width:14px; margin-top:0;"><input type="checkbox" onclick="updateRateUI(this,\''+userId+'\');" checked="checked"></div>' +
        '<div class="cell" style="width:160px; margin-top:3px;">Negotiate Rate ( only one time  )</div></div>';
    }
    html += '</div>';
    html += '<div class="rimd"><br>' +
    '<div align="center" class="rI" id="'+userId+'RateInfo">'+rateInfoMsg+'</div>' +
    '<div class="row">' +
    '<div class="cell" style="width: 55px; margin-top: 3px; margin-left:88px;">New Rate :</div>' +
    '<div class="cell" style="width: 50px; margin-top: 0pt;"><input type="text" size="5" id="'+userId+'NewRate" ></div>' +
    '<div class="cell" style="width:10px; color:#004080; margin-top:3px;">$</div></div>';
    html += '<div class="row" style="width: 200px; margin-left: 90px;" id="'+userId+'BottomButtons">' +
    '<div class="cell chat-billing-small-Btn"><span class="action" style="color:#D34619;" onclick=proposeNewRate("'+userId+'") >Propose</span></div>' +
    '<div class="cell chat-billing-small-Btn"><span class="action" onclick="cancelHireButtonClicked(\'By clicking this, you are going to cancel the rate proposed by Expert. Click OK to continue.\', \''+userId+'\',\'You have canceled the rate sent from Expert. You may indicate your interest over chat and hire him again by clicking on the Hire button.\')">Cancel</span></div></div></div></div>';
	 
    //html+='</div>';
    return html;
//End Rate Session div
}

function cancelHireButtonClicked(confirmMsg, userId, infoMsg)
{
    var html = '<div style="width: 557px; height: auto;">';
    html += '<table id="corner_dialog_table0" align="center" class="corner_dialog_table" style="width: 100%; height: auto;">';
    html += '<tr>';
    html += '<td class="corner_topleft_green"></td>';
    html += '<td class="corner_topborder_green"></td>';
    html += '<td class="corner_topright_grn"></td>';
    html += '</tr>';
    html += '<tr>';
    html += '<td class="corner_borderleft_green"></td>';
    html += '<td id="corner_content_grn0" class="corner_content_grn">';
    html += '<div id="checkoutid"style="width: 100%; height: auto;">';
    html += '<div class="popup-header global-bg-color" style="position:relative; width:539px; margin-left:-10px; margin-top:-10px;">';
    html += '<div style="font-size:14px;">';
    html += 'Cancel Service?';
    html += '<div style="cursor: pointer; position: absolute; font-size: 9px; font-weight: bold; right: 10px; width: auto; top: 10px;">';
    //html += '<a href="javascript:void(0);" id="loginpopup_closeimg" onclick="closecommonconn()" style="color: white;">Close X</a>';
    html += '</div>';
    html += '</div>';
    html += '</div>';
    html += '<div id="CashierInnerDiv">';
    html += '<div class="row" style="padding-top:10px;"><div class="cell nml_bluetxt" style="width:100%;text-align:left;">' + confirmMsg + '</div></div>';
    html += '<div class="row" style="padding-top:20px; height:40px;">';
    html += '<div class="cell" style="width:110px; margin-left: 140px;">';
    html += '<a href="javascript:void(0)" class="global-button global-color small-button-padding" onclick="cancelHire(\''+userId+'\',\''+infoMsg+'\');closecommonconn();">';
    html += 'OK';
    html += '</a>';
    html += '</div>';
    html += '<div class="cell" style="width:110px;">';
    html += '<a href="javascript:void(0)" class="global-button global-color small-button-padding" onclick="closecommonconn();">';
    html += 'Cancel';
    html += '</a>';
    html += '</div>';
    html += '</div>';
    html += '</div>';
    html += '</div>';
    html += '</td>';
    html += '<td class="corner_border_right_grn"></td>';
    html += '</tr>';
    html += '<tr>';
    html += '<td class="corner_bottomleft_grn"></td>';
    html += '<td class="corner_border_bottom_grn"></td>';
    html += '<td class="corner_bottomright_grn"></td>';
    html += '</tr>';
    html += '</table>';
    html += '</div>';



    lid = "ConnectionPopUp";

    commoncallback(html, "ConnectionPopUp");
}
function updateRateUI(negotiateBox, userId)
{
    var billingWinId = userId + "BillingRoot";
    var billingWnd = document.getElementById(billingWinId);


    var currSelectedRateType = "";
    var rdoRatePerMin = document.getElementById(userId+"RdoPerMin");
    if ( rdoRatePerMin && rdoRatePerMin.checked )
    {
        currSelectedRateType = "pm";
    }
    else
    {
        currSelectedRateType = "fix";
    }
	
    if ( negotiateBox.checked)
    {
        billingWnd.innerHTML = getRateUIWithNego(userId, xPackets[userId], currSelectedRateType);
    }
    else
    {
        billingWnd.innerHTML = getRateUI(userId, xPackets[userId], currSelectedRateType);
    }
}
function updateRateInfo(divId, msg1, rate)
{
    document.getElementById(divId).innerHTML='<span>'+msg1+' :</span>&nbsp;<span style=\"color:#004080;\">'+rate+' $</span>';
}

//Set service running ui for expert.
function getServiceUIForExpert(userId,x,enableButton)
{
    var hire = userId + 'BillingRoot';
    var agree = userId+'agree';
    var timer = userId+'timer';
    var timerId = userId+'TimerId';
    var toEzdiaId = userId+'EarnedEzdia';
    var earnedMoneyDiv = userId+'Earned';
    var msgDiv = userId+'msgDiv';
    var btnPauseId = userId+'pause';
    var btnStopId = userId+'stop';
    var btnResumeId = userId+'resume';

    var html ='<div class="ChatBilling_header_nav">';
    html+='<table align="right" width="340" cellpadding="0" cellspacing="0"><tr><td width="5"><img src="'+PRESENCE_SERVICE_URL.replace('$uid$',userId)+ '&rnd=' + Math.random()+'" /></td><td class="topUserName" width="300">Billing</td><td><table align="center" width="12"><tr><td>&nbsp;</td></tr></table></td></tr></table>';
    html+='</div>';
    //End Billing div Header
	
    html += '<div class="base_bg_holder">' +
    '<div class="rimd" style="height:auto;">'+
    '<div align="center" class="hbE">You are hired by Explorer for following cost</div>';
    if (x.getAttribute("t") == "fix")
    {
        html += '<div align="center" style="padding:5px; padding-top:0;"><span style="color:#666;">Fix Rate :</span>&nbsp;<span>'+x.getAttribute("fr")+' $</span></div>';
    }
    else
    {
        html += '<div align="center" style="padding:5px; padding-top:0;"><span style="color:#666;">Rate/Min :</span>&nbsp;<span>'+x.getAttribute("vr")+' $</span></div>';
    }
    html += '</div>' +
    '<div class="thd" style="border-top:1px solid #E5E5E5; text-align:center; padding-top:10px;"> Duration : ' +
    '<b id="'+timerId+'">00:00</b> &nbsp;' +
    '&nbsp;mm:ss' +
    '</div>'+
    '<div class="row thd" style="height:70px;">'+
    '<div class="cell eMtxt">Earned Money :</div>'+
    '<div class="cell emCounter" id="'+earnedMoneyDiv+'">'+((x.getAttribute("t") == "fix")?'0.00':'0.00')+' $</div>'+
    '</div>';
	
    if (enableButton)
    {
        html += '<div class="row enableButton">' +
        '<div class="cell cell-search-btn4" id="'+btnPauseId+'" style="display:block"><span class="action" onclick="requestPauseService(\''+userId+'\')" style="color:#FF3300;">Pause Service</span></div>' +
        '<div class="cell cell-search-btn4" id="'+btnResumeId+'" style="display:none"><span class="action" onclick="resumeService(\''+userId+'\')" style="color:#330099;">Resume Service</span></div>' +
        '<div class="cell cell-search-btn4" id="'+btnStopId+'" style="display:block"><span class="action" onclick="stopService(\''+userId+'\', false)" style="color:#FF0033;">Stop Service</span></div>' +
        '</div>';
    }

    html +='</div>';

    return html;
}
//Get service UI for explorer.
function getServiceUI(userId,x)
{
    var hire = userId + 'BillingRoot';
    var agree = userId+'agree';
    var timer = userId+'timer';
    var timerId = userId+'TimerId';
    var btnStartId = userId+'start';
    var btnPauseId = userId+'pause';
    var btnStopId = userId+'stop';
    var btnResumeId = userId+'resume';
    var msgDiv = userId+'msgDiv';
    var availableBalance= userId + 'AvalBalance';
    var timeAvailable= userId + 'timeAvailable';

    var html ='<div class="ChatBilling_header_nav">';
    html+='<table align="right" width="340" cellpadding="0" cellspacing="0"><tr><td width="5"><img src="'+PRESENCE_SERVICE_URL.replace('$uid$',userId)+ '&rnd=' + Math.random()+'" /></td><td class="topUserName" width="300">Billing</td><td><table align="center" width="12"><tr><td>&nbsp;</td></tr></table></td></tr></table>';
    html+='</div>';
    //End Billing div Header


    //start Fix Rates div
    html += '<div class="base_bg_holder">' +
    '<div class="rimd" style="height:auto;">' +
    '<div align="center" class="hbE">You have hired Expert for following cost</div>';
    if (x.getAttribute("t") == "pm")
    {
        html += '<div align="center" style="padding:5px; padding-top:0;"><span style="color:#666;">Rate/Min :</span>&nbsp;<span>'+x.getAttribute("vr")+' $</span></div>';
    }
    else
    {
        html += '<div align="center" style="padding:5px; padding-top:0;"><span style="color:#666;">Fix Rate :</span>&nbsp;<span>'+x.getAttribute("fr")+' $</span></div>';
    }
    html += '</div>';
	

    html += '<div class="row thd" style="border-top:1px solid #E5E5E5;">';
    html += '<div class="cell" style="padding-left:8px; width:92px;">Available Balance :</div>';
    html += '<div class="cell" style="width:105px;"><b id="'+availableBalance+'">'+myBalance+' $</b></div>';
	
    html += '<div class="cell afl" onClick="showcommondiv(\'AddFund.do\', \'ConnectionPopUp\',\'ConnectionPopUp\');currentWinRemoteUserId='+userId+';">Add funds</div></div>';
    if (x.getAttribute("t") == "pm")
    {
        html += '<div class="row thd">' +
        '<div class="cell" style="width: 200px; padding-left: 23px;">Time Available : ' +
        '<span style="font-weight:bold;">&nbsp;<span id="'+timeAvailable+'">'+getTimeAvailableBeforeStartService(x.getAttribute("vr"))+'</span>&nbsp;mins</span></div>';
    }

    html += '<div class="row thd" style="height:80px">'+
    '<div class="cell eMtxt" style="width:50px;">Duration :</div>' +
    '<div class="cell emCounter"><span id="'+timerId+'">00:00:00</span>' +
    '<div class="emTimer">hh : mm : ss</div></div></div>';

    html += '<div class="row enableButton">' +
    '<div class="cell cell-search-btn4" id="'+btnStartId+'"><span class="action" onclick="startService(\''+userId+'\')" style="color:#76AE31;">Start Service</span></div>' +
    '<div class="cell cell-search-btn4" id="'+btnPauseId+'" style="display:none"><span class="action" onclick="requestPauseService(\''+userId+'\')" style="color:#FF3300;">Pause Service</span></div>' +
    '<div class="cell cell-search-btn4" id="'+btnResumeId+'" style="display:none"><span class="action" onclick="resumeService(\''+userId+'\')" style="color:#330099;">Resume Service</span></div>' +
    '<div class="cell cell-search-btn4" id="'+btnStopId+'" slyle="display:none"><span class="action" id="'+btnStopId+'span" onclick="stopService(\''+userId+'\',false)" style="color:gray;">Stop Service</span></div>' +
    '</div></div>';

    return html;
}

function getTimeAvailableBeforeStartService(pmRate)
{
    try
    {
        var dpmRate = parseFloat(pmRate);
        var mins = myBalance / dpmRate;
        //alert(roundNumber(mins,2) + " " +  myBalance + " " + dpmRate);
        return roundNumber(mins,0) + ":00";
    }
    catch (e)
    {
        return "--:--";
    }
	
}
//Get summer info UI
function getSummaryInfo(userId, time, amt, bal)
{

    var html ='<div class="ChatBilling_header_nav">';
    html+='<table align="right" width="340" cellpadding="0" cellspacing="0"><tr><td width="5"><img src="'+PRESENCE_SERVICE_URL.replace('$uid$',userId)+ '&rnd=' + Math.random()+'" /></td><td class="topUserName" width="300">Billing</td><td><table align="center" width="12"><tr><td>&nbsp;</td></tr></table></td></tr></table>';
    html+='</div>';
    //End Billing div Header

    html += '<div class="base_bg_holder">' +
    '<div class="thd" style="height: auto;">' +
    '<div class="rimd" style="height:auto; margin: 0px 4px 4px;">'+
    '<div align="center" class="hbE">Successfully completed the service.</div>'+
    '<div align="right" class="fwt"><span>Served time:</span>&nbsp;<span>'+time+'</span>&nbsp;<span>min</span></div>'+
    '<div align="right" class="fwt"><span>Deducted amount from account:</span>&nbsp;<span>'+roundNumber(amt,2)+'</span><span>$</span></div>'+
    '<div align="right" class="fwt"><span>Available Balance :</span>&nbsp;<b>'+roundNumber(bal,2)+'</b>&nbsp;<b>$</b></div><br>'+
    '</div>'+
    '</div>'+
    '<div class="row" style="margin-left: 140px; width: 175px;">'+
    '<div class="cell chat-billing-small-Btn"><span class="action" onclick="showFeedBackForm(\''+userId+'\')">Next</span></div>'+
    '</div>'+
    '</div>';
    return html;

}
//get summery info ui for expert.
function getSummaryInfoForExpert(userId, time, amt, bal)
{
    var html ='<div class="ChatBilling_header_nav">';
    html+='<table align="right" width="340" cellpadding="0" cellspacing="0"><tr><td width="5"><img src="'+PRESENCE_SERVICE_URL.replace('$uid$',userId)+ '&rnd=' + Math.random()+'" /></td><td class="topUserName" width="300">Billing</td><td><table align="center" width="12"><tr><td>&nbsp;</td></tr></table></td></tr></table>';
    html+='</div>';
    //End Billing div Header

    html += '<div class="base_bg_holder">' +
    '<div class="thd" style="height: auto;">' +
    '<div class="rimd" style="height:auto; margin: 0px 4px 4px;">'+
    '<div align="center" class="hbE">Successfully completed the service.</div>'+
    '<div align="right" class="fwt"><span>Served time:</span>&nbsp;<span>'+time+'</span>&nbsp;<span>min</span></div>'+
    '<div align="right" class="fwt"><span>Earned Amount:</span>&nbsp;&nbsp;<span>'+roundNumber(amt,2)+'</span><span>$</span></div>'+
    '<div align="right" class="fwt"><span>Available Balance :</span>&nbsp;<b>'+roundNumber(bal,2)+'</b>&nbsp;<b>$</b></div><br>'+
    '</div>'+
    '</div>'+
    '<div class="row" style="margin-left: 140px; width: 175px;">'+
    '<div class="cell chat-billing-small-Btn"><span class="action" onclick="showFeedBackForm(\''+userId+'\')">Next</span></div>'+
    '</div>'+
    '</div>';
    return html;

}

//Show feedback UI form on given user window.
function showFeedBackForm(userId)
{
    var billingWinId = userId + "BillingRoot";
    var billingWnd = document.getElementById(billingWinId);
    billingWnd.innerHTML = getFeedbackUIForm(userId, 'Service');
    billingWnd.style.display ='';
}

//get feedback form ui
function getFeedbackUIForm(userId, name)
{
    var html ='<div class="ChatBilling_header_nav">';
    html+='<table align="right" width="340" cellpadding="0" cellspacing="0"><tr><td width="5"><img src="'+PRESENCE_SERVICE_URL.replace('$uid$',userId)+ '&rnd=' + Math.random()+'" /></td><td class="topUserName" width="300">Feedback</td><td><table align="center" width="12"><tr><td>&nbsp;</td></tr></table></td></tr></table>';
    html+='</div>';
    //End Billing div Header

    html+='<div class="base_bg_holder">'+
    '<div class="thd" style="height: auto;">'+
    '<div class="rimd" style="height:auto; margin: 0px 4px 4px;">'+
    '<div class="ChatBilling_sendRate_txt">Give Reviews for the '+name+'</div>'+
    '<div id="BillingErrorMess" class="msgYellow chatErrorDisplay" style="display:none;"></div>'+
    '<div style="font-weight: bold; padding-left: 20px;">Over all Service</div>'+
    '<div class="row" style="height:15px;">'+
    '<div class="cell fct"><input type="radio" id="'+userId+'rating5" name="'+userId+'rating"></div>'+
    '<div class="cell" style="width:55px;">Excellent</div>'+
    '<div class="cell fct"><input type="radio" id="'+userId+'rating4" name="'+userId+'rating"></div>'+
    '<div class="cell" style="width:65px;">Very Good</div>'+
    '<div class="cell fct"><input type="radio" id="'+userId+'rating3" name="'+userId+'rating"></div>'+
    '<div class="cell" style="width:45px;">Good</div>'+
    '</div>'+
    '<div class="row" style="height:25px;">'+
    '<div class="cell fct"><input type="radio" id="'+userId+'rating2" name="'+userId+'rating"></div>'+
    '<div class="cell" style="width:55px;">Average</div>'+
    '<div class="cell fct"><input type="radio" id="'+userId+'rating1" name="'+userId+'rating"></div>'+
    '<div class="cell" style="width:45px;">Poor</div>'+
    '</div>'+
    '</div>'+
    '</div>'+
    '<div class="fcct">Other Comments</div>'+
    '<div align="center"><textarea cols="45" rows="3" id="'+userId+'FeedbackText"></textarea></div>'+
    '<div class="row" style="width:295px;">'+
    '<div class="cell" style="padding-left: 90px; width: 116px;">'+
    '<div class="blueBtn"><span class="action" onclick="closeFeedBackForm(true, \''+userId+'\')">Submit & Close</span></div>'+
    '</div>'+
    '<div class="cell" style="width: 80px; padding-top: 10px; margin:0"><a href="javascript:void(0)" style="text-decoration:underline;" onclick="closeFeedBackForm(false, \''+userId+'\')">Review Later</a></div>'+
    '</div>'+
    '</div>';
	 
    return html;
}

function closeFeedBackForm(isSubmit, userId)
{
    if( isSubmit )
    {
        var rating = -1;
        if ( document.getElementById(userId+'rating5').checked)
        {
            rating = 5;
        }
        else if ( document.getElementById(userId+'rating4').checked)
        {
            rating = 4;
        }
        else if ( document.getElementById(userId+'rating3').checked)
        {
            rating = 3;
        }
        else if ( document.getElementById(userId+'rating2').checked)
        {
            rating = 2;
        }
        else if ( document.getElementById(userId+'rating1').checked)
        {
            rating = 1;
        }
        if (rating == -1)
        {
            document.getElementById("BillingErrorMess").style.display = '';
            document.getElementById("BillingErrorMess").innerHTML = 'Please select rating to this service.';
            window.setTimeout('cleardiv("BillingErrorMess")',5000);
            return;
        }
        var feedbacktxt = document.getElementById(userId+'FeedbackText').value;

        //alert("Rating: " + rating + "\n" + feedbacktxt);
        addInfoToChatWindow(userId, '<div class="chatuseragree">Thanks for your feedback.</div>');
        chatFeedBackWebHit(otherUserId, rating, feedbacktxt, 'noDiv');
    }
    var billingWinId = userId + "BillingRoot";
    var billingWnd = document.getElementById(billingWinId);
    billingWnd.style.display ='none';
}
function move(theHandle,theRoot){
    var handle=document.getElementById(theHandle);
    var root = document.getElementById(theRoot);
    Drag.init(handle, root);
}


onerror = function(e) {
    // document.getElementById('err').innerHTML = '';
    if (typeof(con) != "undefined" && con.connected()) {
    //con.disconnect();
    }
    return false;
};

onunload = function() {
    if (typeof(con) != 'undefined') {
        // save backend type
        if (con._hold) // must be binding
        {
            (new JSJaCCookie('btype','binding')).write();
        }
        else
        {
            (new JSJaCCookie('btype','polling')).write();
        }
        if (con.suspend)
        {
            con.suspend();
        }
    }
};

var iCordX=0, iCordY=0;

function resizeChatWindow(user) //Gariam: Not sure it is used or not
{
    var msgArea = user + 'msgArea';
    var inputArea = user + 'inputArea';
    var chatBody = user + 'chatBody';
    //var chatTop = user+ 'chatTop';
    var mainPane  = user + 'pane';
    var mainRoot = user + 'Root';
    if (document.getElementById(mainRoot).style.height != '0px') {
        document.getElementById(inputArea).style.display='none';
        document.getElementById(msgArea).style.display='none';
        document.getElementById(chatBody).style.display='none';
        //document.getElementById(chatTop).style.display='none';
        document.getElementById(mainPane).style.display='none';
        document.getElementById(mainRoot).style.height='0px';
        return;
    }
    document.getElementById(mainRoot).style.height='262px';
    document.getElementById(inputArea).style.display='';
    document.getElementById(msgArea).style.display='';
    document.getElementById(chatBody).style.display='';
    //document.getElementById(chatTop).style.display='';
    document.getElementById(mainPane).style.display='';
}
//Open chat window for given user information
function openChatWindow(user,catname,displayname,imgurl,skypeid,position,company,chatEvent) {
    if (arDhtmlWindows[user])
    {
        arDhtmlWindows[user].show(arDhtmlWindows[user]);
        return;
    }
    var html = '';
    if(login_user == null || login_user == '')
    {
        ModalPopup('NewLoginpopupdiv','');
        document.getElementById('login_details').value = 'chat:'+user+':'+catname+':'+displayname+':'+imgurl;
    }
    else
    {
        if(displayname == undefined){
            checkInChatGroup(user);
            displayname = chatwith;
        }
        if(!checkInChatGroup2(user)){
            getUserData2('getUserData.do',user,0);
        }
        lastMessageSenderName[user] = "";
        var category=catname;
        var mainRoot = user + 'Root';
        var mainPane = user + 'pane';
        var movepane = user + 'move';
        var msgArea = user + 'msgArea';
        var inputArea = user + 'inputArea';
        var minIcon = user + 'minIcon';
        var chatBody = user + 'chatBody';
        var hire = user + 'BillingRoot';
        var stopButton = user+'stopBtn'
        var hireBtn = user+'hireBtn';
        hire1= user+'BillingTop';
        var agree = user+'agree';
        var agree2 = user+'agree2';
        var agreeFunds = user+'agreeFunds';
        //var chatTop = user + 'chatTop';
        var avtar = '../static/images/newUserImg.png';
        var status = user+'status';
        var formArea = user+'formArea';
        var title = position;
        var companyName = company;
        var timer = agree+'timer';
        var secs = timer+'seconds';
        var display = timer+'display';
        var msgDiv = user+'msgDiv';
        var checkBox = user+'checkBox';
        var checkBoxError = user+'checkBoxError';

        var rateSession=user+'rateSession';
        if (document.getElementById(mainRoot)) {
            document.getElementById(mainRoot).style.display='';
            return;
        }
        var availableBalanceSpan = login_user + 'availableBalance';
        var rpmSpan = user +'rpm';
        var fixSpan = user +'fixedRate';
        var MoveDiv = user + 'MoveDiv';
        var divwin = user + 'divwin';

        html+='<div id="'+mainRoot+'" >';
        //html+='<div id="'+movepane+'" onmouseover="javascript:void(0);move(\'' + movepane + '\',\'' + mainRoot + '\')"; style="position: absolute; width: 357px; height: 30px; z-index: 10; background-image: url(../static/images/chatTopBar.png); background-repeat: no-repeat; left: 0px; top: 16px;">';
        //html+='<table  align="center" width="340" cellpadding="2" cellspacing="5"><tr><td width="10"><img id="' + status + '" alt="" src="../static/images/status_green.png"/></td><td class="topUserName">' + displayname + '</td><td><table align="center" width="42"><tr><td><img id="' + minIcon +'" onclick="resizeChatWindow(\'' + user + '\')" alt="" src="../static/images/minimizeImg.png" style="cursor:pointer"/></td><td><img alt="" src="../static/images/closeImg.png" onclick="document.getElementById(\'' + mainRoot + '\').style.display=\'none\';" style="cursor:pointer"/></td></tr></table></td></tr></table>';
        //html+='</div>';

        html+='<div id="'+mainPane+'" class="mainChatWinBG">';
        html+='<div id="UserDetailsDiv">';
        html+='<div id="UserNameDiv">';
        html+='<h1 style="font-size: 12px;">' + displayname + '</h1></div>';
        html+='<div id="UserCompanyDetail">';
        if(title && title !='undefined'){
            html+=''+title+' <br />';
        }
        if(companyName && companyName!='undefined'){
            html+='' + companyName + '';
        }

        html+='</div>';
        html+='<div id="UserImage">';
        if(imgurl) {
            html+='<img alt="" src="' + imgurl + '" height="60"/></div>';
        }
        else{
            html+='<img alt="" src="' + avtar + '" width="60" height="67"/></div>';
        }
        if(skypeid && skypeid != '' && skypeid!='undefined'){
            html+='<div id="skypeImage"><a href="skype:'+skypeid+'?call"/><img src="../static/images/skype.png" border="0" alt="skype"/></a></div>';
        }
        else{
            html+='<div id="skypeImage"><img src="../static/images/noskype.png" border="0" alt="skype"/></div>';
        }
        if(!chatFlag) {
            html+='<div id="'+hireBtn+'" class="hireBtn"><a href="javascript:void(0)" class="global-button global-color small-button-padding" onclick=openRequestUIForHire("'+user+'")>Hire</a></div>';
            html+='<div id="'+stopButton+'" class="hireBtn" style="display:none;"><a href="javascript:void(0)" class="global-button global-color small-button-padding" onclick=stopService("'+user+'",false)>Stop</a></div>';
        }
        html+='</div>';
        html+='<div id="'+chatBody+'" class="ChatBody"></div>';
        html+='<div id="'+inputArea+'" class="ChatArea">';
        //html+='<form onsubmit="return sendMsg(this);" name="sendForm">';
        html+='<textarea id="'+msgArea+'" name="msg" class="userstxt" style="width: 330px; border:1px solid #FFF; height:1.4em;" onKeyPress="sendMsg(this, event, \''+user+'\')" /></textarea>';
        //html+='<input type="hidden" tabindex="1" value="' + user +'" name="sendTo"/>';
        // html+='</form>';
        html+='</div>';
        //html+='<div id="OptionsDiv" style="position: absolute; width: 60px; height: 14px; z-index: 4; left: 10px; top: 255px; font-weight: bold;">';
        //html+='Options&nbsp;&nbsp;<img alt="" height="6" src="../static/images/chtaArrowSide.png" width="6" /></div>';
        //html+='<div id="RightSideSizeImg" style="position: absolute; width: 10px; height: 10px; z-index: 5; left: 335px; top: 258px">';
        //html+='<img alt="" height="10" src="../static/images/chatRightWinSizeImg.png" width="10" /></div>';
        html+='</div>';


        //***********************************Billing****************************//
        //start Billing div
        html+='<div id="'+hire+'" class="ChatBillingBG" style="display:none;">';

  
        html+='</div>';
        //End Rates div

       
        //document.getElementById('chatwindow').innerHTML += html;
        var dhtmlwindowholder = document.getElementById('chatwindow');
        if(dhtmlwindowholder !=null){
            dhtmlwindowholder.innerHTML += html;
        }
        var chatWindowY;
        if(chatEvent){
            chatWindowY =chatEvent.clientY-20;
        }else{
            chatWindowY =100;
        }
        //divwin=dhtmlwindow.open(MoveDiv,'div',mainRoot,displayname, 'width=357px,height=254px,left=200px,top='+chatWindowY+'px,resize=1,scrolling=1');
        divwin=dhtmlwindow.open(MoveDiv,'div',mainRoot,displayname, 'width=354px,height=254px,left=200px,top='+chatWindowY+'px,scrolling=1,userid='+user);
        arDhtmlWindows[user] = divwin;
        divwin.onclose=function(){
            //alert(dhtmlwindowholder.innerHTML);
            dhtmlwindowholder.innerHTML=' ';
            return true;
        };
    }
    addTrackEvent("button","chat","open");
    updateWindowHeightWidth();
}

function cancelEventBubbeling(e)
{
    if(document.all)e = event;
    e.cancelBubble = true;
    if(window.ActiveXObject)    
        event.returnValue = false;    
    else
        e.preventDefault();
}

function clearUserBalanceChecker()
{
    if (balCheckTimer != null)// Stop Bal Timeer if running
    {
        clearTimeout(balCheckTimer);
        balCheckTimer = null;
    }
}
function startUserBalanceChecker()
{
    getUserAccountBalance(currentWinRemoteUserId);
    balCheckTimer = setTimeout("startUserBalanceChecker()", 15000);
}
/******************UI Code Ends**************************/

// Used to get local user information 
function checkInChatGroup(user_id,aJSJaCPacket){ 
    var html='';
    var i;
    var date = new Date();
    for(i=0;i<ChatUsers.length;i++){
        if(ChatUsers[i].userid == user_id){
            chatwith = ChatUsers[i].name;
            company1 = ChatUsers[i].company;
            position1 = ChatUsers[i].position;
            skypeid1 = ChatUsers[i].skypeid;
            //html += '<div class="chatuser username2">' + chatwith + '</div>';
            //html += '<table class="chatuser username2"><tr><td width="300">' + chatwith + '</td></tr></table>';
            //html += '<div class="usertext">' + aForm.msg.value + '</div>';
            
			
            // if(html.indexOf("hire" != -1)){
            //       requestForHire(user._node);
            //}
            //html+=playSound("message_recv");
            if(aJSJaCPacket.getFromJID()!=null ) {

                var chatBody = user_id + 'chatBody';
                var chatID = document.getElementById(chatBody);
                if (!chatID) {
                    initialJSJaCMessage = aJSJaCPacket;
                    getUserThumbnail("getUserImage.do", user_id);

                }
                if (aJSJaCPacket)
                {
                    processXMPPMessage(chatwith, aJSJaCPacket);
                //addMessageToChatWindow(chatwith, user_id, aJSJaCPacket.getBody().htmlEnc());
                }
				

            }
            return true;
            break;
        }
    }
    return false;
}
//Used
function getUserData(actionURL,uid,aJSJaCPacket,bo){
    initialJSJaCMessage = aJSJaCPacket;
    showResultWithQueryStr1(actionURL, null, callbackuserdataforchat,"uid="+escape(uid)); //Gariam: Ajax hit to Java.
    return true;
}
//Used
function getUserThumbnail(actionURL,uid){
    showResultWithQueryStr1(actionURL, null, callbackuserthumbnail,"uid="+escape(uid));
    return true;
}
//Used
function getUserData2(actionURL,uid,bo){
    showResultWithQueryStr1(actionURL, null, callbackuserpresence,"uid="+escape(uid));
    return true;
}

// Callback for getUserData
function callbackuserdataforchat(response){ 
    var chatID
    var result =  eval('('+chattrim(response)+')');
    if(ChatUsers.length == 0){
        ChatUsers[ChatUsers.length] = new ChatArray(result.username, result.firstname,result.company,result.position,result.skypeid);
        chatwith = result.firstname;
        position1= result.position;
        company1= result.company;
        skypeid1 = result.skypeid;

        oDbg.log("Message :" + initialJSJaCMessage.getBody().htmlEnc() );

        //html+=playSound("message_recv");
        if(initialJSJaCMessage.getFromJID()!=null ) {
            chatID = document.getElementById(result.username + 'chatBody');
            if (!chatID) {
                getUserThumbnail("getUserImage.do", result.username);

            }
            else
            {
                processXMPPMessage(chatwith, initialJSJaCMessage);
            }
            
        //addMessageToChatWindow(chatwith, result.username, jsjacpacket.getBody().htmlEnc());
        }
    }
    else{
        ChatUsers[ChatUsers.length] = new ChatArray(result.username, result.firstname,result.company,result.position,result.skypeid);
        chatwith = result.firstname;
        position1= result.position;
        company1= result.company;
        skypeid1 = result.skypeid;
        oDbg.log("Message :" + initialJSJaCMessage.getBody().htmlEnc() );
        //html+=playSound("message_recv");
        if(initialJSJaCMessage.getFromJID()!=null ) {
            chatID = document.getElementById(result.username + 'chatBody');
            if (!chatID) {
                getUserThumbnail("getUserImage.do", result.username);
            }
        //processXMPPMessage(chatwith, initialJSJaCMessage);
        //addMessageToChatWindow(chatwith, result.username, jsjacpacket.getBody().htmlEnc());
        }
    }

}
// Callback for getUserData2
function callbackuserpresence(response){
    var chatBody;
    var result =  eval('('+response+')');
    if( result.presence == 0)
    {
        chatBody= document.getElementById(result.username+'chatBody');
        if (chatBody) {
            chatBody.innerHTML += '<br> User is not logged in for Chat or Hire <br>';
        }
        checkPresence=0;
    }
    else{
        ChatUsers[ChatUsers.lengh] = new ChatArray(result.username, result.firstname);
        chatwith = result.firstname;
    }
}

// Callback for getUserThumbnail
function callbackuserthumbnail(response){
    var result =  eval('('+response+')');
    avtar1=result.image;
    openChatWindow(result.username,"",chatwith,avtar1,skypeid1,position1,company1);
    processXMPPMessage(chatwith, initialJSJaCMessage);
}

// Called from openChatWindow
function checkInChatGroup2(user_id){

    if(ChatUsers.length>0){
        for(i=0;i<ChatUsers.length;i++){
            if(ChatUsers[i].userid == user_id){

                return true;
            }
        }
        return false;
    }
    return false;
}

var playSounds = true;

var SOUNDS = new Object();

//SOUNDS['message_recv'] = "../static/sounds/alert.wav"
//SOUNDS['message_recv'] = "../static/sounds/message_recv.swf"
SOUNDS['message_recv'] = "../static/sounds/message1.mp3"
SOUNDS['message_queue'] = "../static/sounds/message_queue.swf"
SOUNDS['chat_recv'] = "../static/sounds/chat_recv.swf"
SOUNDS['chat_queue'] = "../static/sounds/chat_queue.swf"
SOUNDS['online'] = "../static/sounds/online.swf"
SOUNDS['offline'] = "../static/sounds/offline.swf"
SOUNDS['startup'] = "../static/sounds/startup.swf"
SOUNDS['connected'] = "../static/sounds/connected.swf"

function playSound(action) {
    try
    {
        var frameD = frames["sound_iframe"].document;
        var html = "<embed src=\""+SOUNDS[action]+"\" width=\"1\" height=\"1\" quality=\"high\" pluginspage=\"http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash\" type=\"application/x-shockwave-flash\">";
        frameD.open();
        frameD.write(html);
        frameD.close();
    }
    catch (ex){}
}
function roundNumber(num, dec) {
    var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
    return result;
}
/***************************** Ashish Code *************************/
//Query list of my experties from server.
function getMyExpertise(expertiesComboId){

    showResultWithQueryStr1("getChatExpertise.do", expertiesComboId, getMyExpertise_Callback, null);

}
function getMyExpertise_Callback(result,pid){
    //alert(result);
    jsonString = eval('('+chattrim(result)+')');
    var j = jsonString.length;
    var k ;
    var carCombo = document.getElementById(pid);
    if(j == 1 && jsonString[0].category_id == "0")
    {
        carCombo.options[0] = new Option("Technology and Computer", "0");
        carCombo.selectedIndex = 0;
        return;
    }
    else{
        if (carCombo)
        {
            for(var i=0;i<jsonString.length;i++){
                if(jsonString[i].category_id == 'Select Category...'){
                    k=i;
                }
                carCombo.options[i] = new Option(jsonString[i].category_id, jsonString[i].rpm);
            }
            carCombo.selectedIndex =k;
        }
    }
    if (carCombo.options.length == 0)
    {
        carCombo.options[0] = new Option("Technology and Computer", "0");
    }
    
}
//Get user accont balance.
function getUserAccountBalance(userId){
    showResultWithQueryStr1('getUserAmount.do',userId,getUserAccountBalance_Callback,null,true,false);
}
function getUserAccountBalance_Callback(result,pid){
    jsonString = eval('('+chattrim(result)+')');
    var i =jsonString.length;
    if(i==1){
        try
        {
            var myBalance1 = roundNumber(parseFloat(jsonString[0].totaldollars), 2);
            if (myBalance != myBalance1 && balCheckTimer != null)// Clear timer
            {
                clearUserBalanceChecker();
            }
            myBalance = myBalance1;
            var AvalBalance = document.getElementById(currentWinRemoteUserId + 'AvalBalance');
            if (AvalBalance)
            {
                AvalBalance.innerHTML = myBalance + "&nbsp;$";
            }
        }
        catch (ex){}
    // document.getElementById(pid).innerHTML = '';
    // document.getElementById(pid).innerHTML="Total Amount: "+jsonString[0].totaldollars+
    //   +'$<br/>Bought Amount: '+jsonString[0].boughtdollars+"$ <br/>Earned Amount: "+jsonString[0].earneddollars;
    }
    return;
}

//FUCNTION FOR INITIATE CHAT ON AGREE BUTTON CLICK
/*
*initiateOnAgree('agreeForChat.do',divid,'100300303','10','per min or fix')
*0 for per min and 1 for fix
*/

function initiateOnAgree(divid,expertID,sessionRate,rateType){

    var e = expertID; // Expert id value
    var r = sessionRate; // rate
    var rt=rateType; // Rate type
    var qry="e="+e+"&r="+r+"&rt="+rt;
    showResultWithQueryStr1('agreeForChat.do',divid,initiateOnAgree_CallBack,qry);
    
}
var remark_transid;
function initiateOnAgree_CallBack(result,pid){
    jsonString = eval('('+result+')');
    var i =jsonString.length;
    if(i==1){
        remark_transid=jsonString[0].transid;
        xBillingData[pid].billingTranId = jsonString[0].transid;
    }
    return;
}

/* FUNCTION FOR DIFFERNT - DIFFERENT CHAT EVENT
*chatEvent('',divid,0,'10101010','10.0');
*  eventid, ev for event request like start=0, stop=1, pause=2, resume=3, cancle=4
*  transid, tid for transaction id
*  duration for chat duration
*  rate,r for rate per min
*  expert, e expert id
*/
function chatBillingEvent(divid,eventId,expert,rate,ratetype){
    var qry;
    if(eventId == 0)//start
        qry="ev="+eventId+"&tid="+xBillingData[divid].billingTranId;
    else if(eventId == 1)//stop
        qry="ev="+eventId+"&tid="+xBillingData[divid].billingTranId+"&dt="+(ms/1000/60)+"&e="+expert+"&r="+rate+"&rt="+ratetype;
    else if(eventId == 2)//pause
        qry="ev="+eventId+"&tid="+xBillingData[divid].billingTranId+"&dt="+(ms/1000/60);
    else if(eventId == 3)//resume
        qry="ev="+eventId+"&tid="+xBillingData[divid].billingTranId;
    else if(eventId == 4)//cancle
        qry="ev="+eventId+"&tid="+xBillingData[divid].billingTranId;
    else if(eventId == 5)//update
        qry="ev="+eventId+"&tid="+xBillingData[divid].billingTranId+"&dt="+(ms/1000/60);
    showResultWithQueryStr1('chatEventHandler.do',divid,chatBillingEvent_CallBack,qry);

}

function chatBillingEvent_CallBack(result,pid){
    //document.getElementById(pid).innerHTML = '';
    jsonString = eval('('+result+')');
    var i =jsonString.length;
    if(i==1 && jsonString[i-1].response){
        var   resp = jsonString[i-1].response;
        if(resp == 'success'){
        //document.getElementById(pid).innerHTML="Thanks";
        }
        else if(resp == 'fail'){
    //document.getElementById(pid).innerHTML="Error!Please Try After Some Time";
    }
    }
    else{
    //document.getElementById(pid).innerHTML="Please Try After Some Time";
    }
    return;
}

/* FUNCTION FOR TO GIVE FEEDBACK ON CHAT
*chatEvent('10010101',1,'he is a goog exoert',divid);
*  uid = user id to whom to give the feedback
*  rating = 1-5
*  review = text message
*  divid = to show the response text
*/
function chatFeedBackWebHit(uid,rating,review,divid){
    //alert("Submitting feedback");
    var qry = 'user='+uid+'&skillid=0&rating='+escape(rating)+'&type=chat&remark='+remark_transid+'&review='+escape(review);
    //showResultWithQueryStr1('checkfeedback.do',divid,chatFeedBack_CallBack,qry);
    showResultWithQueryStr('checkfeedback.do',divid,commoncallback,qry,true);
}

function chatFeedBack_CallBack(result,divid){
//alert(result);
}
/***************************** Ashish Code Ends*************************/

