sUrl = "ContactServlet";
var hrefPageHistoryId = "hrefPageHistory1Active";
var hrefPageFinishedConferencesId = "hrefPageFinishedConferences1";
var hrefPageActiveConferencesId = "hrefPageActiveConferences1";
var countContacts = 0;
var historyType = 'Active';
var myAccount = true;
var conferenceName = null;


//Add function trim in Class String
//String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ""); };

//function return object of class XMLHttpRequest
function getHTTPRequestObject() {
    var xmlHttpRequest;
        if (typeof ActiveXObject != 'undefined') {
                xmlHttpRequest = new ActiveXObject('Microsoft.XMLHTTP');
        } else if (typeof XMLHttpRequest != 'undefined') {
                xmlHttpRequest = new XMLHttpRequest();
        } else {
                xmlHttpRequest = false;
        }
    return xmlHttpRequest;
}

var httpRequester = getHTTPRequestObject(); //Work object of class XMLHttpRequest

var READY_STATE_COMPLETE=4;

//execute asinhronous GET
function makeAJAXCall(ajaxUrl){
    if (httpRequester) {
        httpRequester.open("GET", ajaxUrl, true);
        httpRequester.onreadystatechange = processResponse;
        httpRequester.send(null);
    }
}

//CallBack-function. Display received asinhronuosly data or error message
function processResponse() {    
    if (httpRequester.readyState == READY_STATE_COMPLETE) {
        if (httpRequester.status==200) {
            var val = httpRequester.responseText;			
            if(val == '!!!!!') Redirect('Home.jsp');
            else if(val.substr(0, 3) == '???') printToPage(val, 4);
			else if(val.substr(0, 3) == '<<<') printToPage(val, 7);
            else if(val.substr(0, 3) == '---') printToPage(val, 5);
            else if(val.substr(0, 3) == '+++') printToPage(val, 6);
            else if(val.substr(0,11) == '<tr bgcolor') printToPage(val, 2);
            else if(val.substr(0,2) == '&&') printToPage(val, 3);
            else printToPage (val, 1);
        } else {
            loadContacts = false;
            var message = "Problem retrieving data. requestStatus="+httpRequester.status+". Message="+httpRequester.statusText;
			getelementbyid('errMsg').innerHTML = message;
			OnDark('errorBox', true, 150, 150);
        }
    }
}

//Display passed HTML into element
//1 - Load Contacts
//2 - Load History
//3 - Load Conference
//4 - Load Finished Conferences
//5 - Load Users
//6 - Load User
function printToPage(value, act){
  if(act == 1)
  {//Contacts
//alert('value = '+value);

    var stop = false;
    var str = value.toLowerCase();

    if(str == "stop") stop = true;
    if(!stop && str.substr(str.length-4) == "stop")
    {        
        value = value.substr(0, value.length-4);
        stop = true;
        loadContacts = false;
    }

    if(value.substr(0,2) == '>>') value=value.substr(2);
    var contacts = value.split('>>');
    
    if(!stop && str != "continue" && (contacts == null || contacts[0].indexOf('&&') == -1))
    {
//alert('error ' + contacts.length);    
        askaError = true;
        stop = true;
        
        if(loadContacts)
        {
            if(contacts == null) value = 'Problems on the Server';
            else value = contacts[0];
        
            //getelementbyid('procWaitTD').style.color = '#ff0000';
            //getelementbyid('procWaitTD').innerHTML = value;
			getelementbyid('procWaitTD').innerHTML = '&nbsp;';
			getelementbyid('errMsg').innerHTML = value;
			OnDark('errorBox', true, 150, 150);			
        }
    }    

    if(!askaError && str!='stop')
    {        
        if(str != "continue")
        {
            var selContacts = getelementbyid('selPossibleContacts');
            var contact = null;            
            for(var i=0; i<contacts.length; i++)
            {
                contact = contacts[i].split('&&');
                    
                countContacts++;
                //alert('name='+contact[0]+'         '+contact[4]);
                if(!isConsist(selContacts, contact[4]))
                {
                    addContactGrid(grid2, contact[0], contact[1], contact[2], getStatusUrl(contact[3]), contact[4]);     
                    selContacts.options[selContacts.options.length] = new Option(contact[4], contact[4], false, false); 
                }
            }
        }

        if(!stop)
        {
            if(loadContacts) getContacts(0, 0, true);
            else getContacts(0, 0, true, true);                                            
        }
    }
    
    if(stop)
    {        
//alert('stop');    
        displayVisible(getelementbyid('processLoad'), false);
        displayVisible(getelementbyid('stopLoad'), false);
        
        getelementbyid('loadContactsBut').disabled = false;
        if(!askaError) getelementbyid('procWaitTD').innerHTML = '&nbsp;';
        
        loadContacts = false;
    }
  }
  else if(act == 2)
  {//History
    resultDiv = getelementbyid('resultHistory'+historyType);

    countPageHistory = value.substr(value.lastIndexOf('</tr>')+5);  
    value = value.substr(0, value.lastIndexOf('</tr>')+5);   

    var htmlText = "<table border='0' cellpadding='0' cellspacing='0' width='100%' style='font-family:Verdana; font-size:11; font-weight:normal; color:#828282;'>" +
                          "<tr><td width='150px'>&nbsp;</td><td width='150px'>&nbsp;</td><td>&nbsp;</td></tr>" +
                            value +
                   "</table>";

    resultDiv.innerHTML = htmlText;
    document.location.replace('#History');
  }
  else if(act == 3)
  {//Conference
    value = value.substr(2);    
    
    var conference = value.split("&&");
    if(conference == null || conference.length <= 1)
    {//ERROR
        var err = null;
        if(conference == null || conference.length < 1) err = "Error on the Server";
        else err = conference[0];
        getelementbyid('errMsg').innerHTML = err;
		OnDark('errorBox', true, 150, 150);
    }
    else
    {     	
        conference[1] = HtmlReplaceAjax(conference[1]);
              
        if(conference[0] != '') countPageHistory = conference[3];

        onSubmit('selWorkContactsDelete');
        deleteSelectedOptions('selWorkContactsDelete');

        if(isPasted)
        {        
            getelementbyid('titleName').innerHTML ='Conference: ' + HtmlReplace(HtmlReplaceAjax(conference[0]));
            getelementbyid('pastSubject').value = conference[1];

            var htmlText = "<select id='selDeleteContacts' multiple size='2' style='display:none;'>";
            htmlText += conference[2] + "</select>";
            getelementbyid('lastParticipantsTD').innerHTML = htmlText;

            clearGrid(grid3);
            fillGrid('selDeleteContacts', grid3);

            var dd = conference[4].split('&');
            getelementbyid('datePast').innerHTML = dd[0];
            getelementbyid('durationPast').innerHTML = dd[1];
        }
        else
        {       
            if(conference[0] == '') getelementbyid('titleName').innerHTML = 'New Conference';
            else
            {
                var online = null;
                if(conference[0].indexOf('&') != -1)
                {
                    online = conference[0].substr(conference[0].indexOf('&')+1).split('&');
                    conference[0] = HtmlReplaceAjax(conference[0].substr(0, conference[0].indexOf('&')));
                   
                    getelementbyid('iActive').innerHTML = online[0];                    
                    getelementbyid('jActive').innerHTML = online[2];                    
                    getelementbyid('oActive').innerHTML = online[3];  

					if(getelementbyid('parts'+idConference) != undefined && getelementbyid('parts'+idConference) != null)
					{
						var ht = online[2]+' ('+online[3]+')';
						getelementbyid('parts'+idConference).innerHTML = ht;
					}
                }

                getelementbyid('titleName').innerHTML ='Conference: ' + HtmlReplace(conference[0]);
            }        
        
            getelementbyid('activeSubject').value = conference[1];

            if(firefox || safari || op)
            {
                getelementbyid('selWorkContacts').innerHTML = conference[2];
            }
            else
            {
                var htmlText = "<select id='selWorkContacts' name='workcontacts' size='2' multiple style='display:none;'>";
                htmlText += conference[2] + "</select>";
                getelementbyid('selWorkContactsTD').innerHTML = htmlText;            
            }
            
            htmlText = "<select id='selPossibleContacts' name='stores' size='2' multiple style='display:none;'>";
            htmlText += conference[4] + "</select>";
            getelementbyid('selPossibleContactsTD').innerHTML = htmlText;
            
            clearGrid(grid2);
            fillGrid('selPossibleContacts', grid2);
            clearGrid(grid1);

            if(idConference > 0)
            {            
                var dd = conference[5].split('&');
                getelementbyid('ttlActive').innerHTML = dd[0];
                getelementbyid('durationActive').innerHTML = dd[1];            

                if(conference[6] == '0') getelementbyid('indicateStatus').checked = false;
                else getelementbyid('indicateStatus').checked = true;
            
                fillGrid('selWorkContacts', grid1);
            }
            else
            {
                document.title='Create a New Conference';
            }            
        }

        if(idConference > 0)
        {
			conferenceName = HtmlReplaceAjax(conference[0]);
            document.title='PersistentIM ' + conferenceName;                        
        }
        
        resetFilter();                
    }
  }
  else if(act == 4)
  {//Finished Conferences
  
        value = value.substr(3);
//alert(value);        
        var countFinishedConferences = value.substr(value.lastIndexOf('</tr>')+5);  
        value = value.substr(0, value.lastIndexOf('</tr>')+5);  
  
        var htmlText = "<table class='table_common' cellpadding='0' cellspacing='0'>" +
                                            "<thead style='font-family:Verdana; font-size:12; font-weight:bold; color:#828282;'>" +
                                                "<tr>" +
                                                    "<td width='150px' align='center'>Conference Name</td>"+
                                                    "<td width='55px' align='center'>Users</td>"+
                                                    "<td width='65px' align='center'>Date</td>"+
                                                    "<td>&nbsp;</td></tr></thead>" +
                                            "<tbody style='font-family:Verdana; font-size:11; font-weight:normal; color:#828282;'>";

        htmlText += value;                                                    
        htmlText += "</tbody></table>";                                                    
        getelementbyid('finishedConferencesTD').innerHTML = htmlText;


        if(isPasted && activeTr!=null && getelementbyid(activeTr)!=undefined && getelementbyid(activeTr)!=null) getelementbyid(activeTr).className='tr_selected_past';
  }
  else if(act == 5)
  {//Users
  
        value = value.substr(3);
//alert(value);                  
        var htmlText = "<table border='0' width='710px' cellpadding='0' cellspacing='0'>"+
                                    "<thead align='center' class='header_params_green' style=\"text-align: left;\">"+
                                        "<tr><td>UserID</td><td>First Name</td><td>Last Name</td><td>IM's</td></tr>"+
                                    "</thead><tbody style='font-family:Verdana; font-size:11; font-weight:normal; color:#828282;'>" +
										"<tr><td width='160px'>&nbsp;</td><td width='160px'>&nbsp;</td><td width='160px'>&nbsp;</td><td>&nbsp;</td></tr>";
        htmlText += value;                                                    
        htmlText += "</tbody></table>"; 
        getelementbyid('usersTD').innerHTML = htmlText;
  }
  else if(act == 6)
  {//User
  
        value = value.substr(3);
//alert(value);

        var user = value.split('&&');

        if(!myAccount)
        {
            getelementbyid('titleName').innerHTML = HtmlReplace(user[0]) + ' Account';
			var us = user[0].replace("\"", "''");
            document.title = 'Edit ' + us + ' Account';
						
			//if(accNames.length == 0 || accNames[accNames.length-1] != user[0]) 
			//accNames[accNames.length] = user[0];
			//alert(accNames.length);
			//alert(accNames[accNames.length-1]);
        }

        getelementbyid('firstName').value = user[1];
        getelementbyid('lastName').value = user[2];
        getelementbyid('userid').value = user[0];
        getelementbyid('email').value = user[3];

        if(firefox || safari || op)
        {
            getelementbyid('selWorkContactsAccount').innerHTML = user[4];
        }
        else
        {
            var htmlText = "<select id='selWorkContactsAccount' name='workcontactsaccount' size='5' multiple style='width:260px;border-color:rgb(207,220,231);border-style:solid;border-width:2px;font-size:13px;'>";
            htmlText += user[4] + "</select>";
            getelementbyid('selWorkContactsAccountTD').innerHTML = htmlText;            
        }

  } else {
		if (act == 7) {//Active Conferences
			value = value.substr(3);
			//							alert(value);        
			//							alert(act);        
			var countActiveConferences = value.substr(value.lastIndexOf('</tr>') + 5);
			
			value = value.substr(0, value.lastIndexOf('</tr>') + 5);
			
			var htmlText = "<table class='table_common' cellpadding='0' cellspacing='0'>" +
			"<thead style='font-family:Verdana; font-size:12; font-weight:bold; color:#787878;'>" +
			"<tr>" +
			"<td width='110px' align='center' style='border-bottom: 1px solid #84bb32; padding-bottom:2px;'>Conference Name</td>" +
			"<td width='55px' align='center' style='border-bottom: 1px solid #84bb32; padding-bottom:2px;'>Users (Online)</td>" +
			"<td width='95px' align='center' style='border-bottom: 1px solid #84bb32; padding-bottom:2px;'>Duration</td>" +
			"<td align='center' style='border-bottom: 1px solid #84bb32;font-size:1px;'>&nbsp;</td></tr></thead>" +
			"<tbody style='font-family:Verdana; font-size:11; font-weight:normal; color:#828282;'>";
			
			htmlText += value;
			htmlText += "</tbody></table>";
			getelementbyid('activeConferencesTD').innerHTML = htmlText;
			
			
			if (isPasted && activeTr != null && getelementbyid(activeTr) != undefined && getelementbyid(activeTr) != null) 
				getelementbyid(activeTr).className = 'tr_selected_past';
		}
	}
}


//Display Contact List
function getContacts(id, psw, isOld, isStop, userId){
    var d = new Date();
    sUrl = "ContactServlet";
    strURL = sUrl+'?id='+escape(id)+'&psw='+escape(psw)+'&tim='+d.getTime();

    if (userId != null) {
		strURL += '&user_id=' + userId;
	}
	
	
    if(!isOld)
    {
        strURL += '&new=1';
        countContacts = 0;
    }
    if(isStop) strURL += '&stop=1';
    loadContacts = true;

//alert(strURL);

    makeAJAXCall(strURL);
}

//Display History List
function getHistory(page, act){
    sUrl = "HistoryServlet";
    var d = new Date();
    
    if(act != undefined && act != null) historyType = act;    
    ChangeValue('pageHistory', page);

    var oldLink = getelementbyid(hrefPageHistoryId);
    if(oldLink != null) oldLink.className = "hrefPageHistory_i";
    hrefPageHistoryId = 'hrefPageHistory' + page + historyType;
    var link = getelementbyid(hrefPageHistoryId);
    if(link != null) link.className = "hrefPageHistory_a";

    if(page > 1) displayVisible(getelementbyid('hrefPrevPageHistory'+historyType), true);
    else displayVisible(getelementbyid('hrefPrevPageHistory'+historyType), false);

    if(page < countPageHistory) displayVisible(getelementbyid('hrefNextPageHistory'+historyType), true);
    else displayVisible(getelementbyid('hrefNextPageHistory'+historyType), false);
    
    var pages = getelementbyid('pagesHistory'+historyType);
    var htmlText = "";

    var i = 1;
    if(page - 10 > 1) i = page - 10;

    if(countPageHistory != 1)
    {
        for(;i<page+10;i++)
        {
            if(i > countPageHistory) break;

            if(page != i) htmlText += "&nbsp;<a id='hrefPageHistory" + i + historyType + "' name='History' href='#' onclick='getHistory(" + i + ");' class='hrefPageHistory_i'>" + i + "</a>";
            else htmlText += "&nbsp;<SPAN id='hrefPageHistory" + i + historyType + "' name='History' class='hrefPageHistorySpan'>" + i + "</SPAN>";
        }
    }
    else htmlText = '&nbsp;';
    pages.innerHTML = htmlText;

    makeAJAXCall(sUrl+'?conference='+idConference+'&page='+page+'&tim='+d.getTime());
}

//Display Conference information
function getConference(confid)
{
//    displayVisible(getelementbyid('errMsg'), false);
//    displayVisible(getelementbyid('selWorkContactsError'), false);

    sUrl = "ConferenceServlet";
    var d = new Date();
    if(deletePastConferenceStarted == false){
        makeAJAXCall(sUrl+'?conference='+confid+'&user='+userid+'&tim='+d.getTime());
    }else{
        deletePastConferenceStarted = false;
    }
}

//Display Active conference list
function getActiveConferences(page){
    sUrl = "ActiveConferencesServlet";
    var d = new Date();
        
    ChangeValue('pageActiveConferences', page);

    var oldLink = getelementbyid(hrefPageActiveConferencesId);
    if(oldLink != null) oldLink.className = "hrefPageHistory_i";
    hrefPageActiveConferencesId = 'hrefPageActiveConferences' + page;
    var link = getelementbyid(hrefPageActiveConferencesId);
    if(link != null) link.className = "hrefPageHistory_a";

    if(page > 1) displayVisible(getelementbyid('hrefPrevPageActiveConferences'), true);
    else displayVisible(getelementbyid('hrefPrevPageActiveConferences'), false);

    if(page < countPageActiveConferences) displayVisible(getelementbyid('hrefNextPageActiveConferences'), true);
    else displayVisible(getelementbyid('hrefNextPageActiveConferences'), false);
   
    var pages = getelementbyid('pagesActiveConferences');
    var htmlText = "";

    var i = 1;
    if(page - 10 > 1) i = page - 10;
    for(;i<page+10;i++)
    {
        if(i > countPageActiveConferences) break;

        if(page != i) htmlText += "&nbsp;<a id='hrefPageActiveConferences" + i + historyType + "' href='#' onclick='getActiveConferences(" + i + ");' class='hrefPageHistory_i'>" + i + "</a>"; 
        else htmlText += "&nbsp;<SPAN id='hrefPageActiveConferences" + i + historyType + "'  class='hrefPageHistorySpan'>" + i + "</SPAN>"; 

    }
    pages.innerHTML = htmlText;

    makeAJAXCall(sUrl+'?page='+page+'&tim='+d.getTime());
}

//Display Finished Conferences List
function getFinishedConferences(page){
    sUrl = "FinishedConferencesServlet";
    var d = new Date();
        
    ChangeValue('pageFinishedConferences', page);

    var oldLink = getelementbyid(hrefPageFinishedConferencesId);
    if(oldLink != null) oldLink.className = "hrefPageHistory_i";
    hrefPageFinishedConferencesId = 'hrefPageFinishedConferences' + page;
    var link = getelementbyid(hrefPageFinishedConferencesId);
    if(link != null) link.className = "hrefPageHistory_a";

    if(page > 1) displayVisible(getelementbyid('hrefPrevPageFinishedConferences'), true);
    else displayVisible(getelementbyid('hrefPrevPageFinishedConferences'), false);

    if(page < countPageFinishedConferences) displayVisible(getelementbyid('hrefNextPageFinishedConferences'), true);
    else displayVisible(getelementbyid('hrefNextPageFinishedConferences'), false);
   
    var pages = getelementbyid('pagesFinishedConferences');
    var htmlText = "";

    var i = 1;
    if(page - 10 > 1) i = page - 10;
    for(;i<page+10;i++)
    {
        if(i > countPageFinishedConferences) break;

        if(page != i) htmlText += "&nbsp;<a id='hrefPageFinishedConferences" + i + historyType + "' href='#' onclick='getFinishedConferences(" + i + ");' class='hrefPageHistory_i'>" + i + "</a>"; 
        else htmlText += "&nbsp;<SPAN id='hrefPageFinishedConferences" + i + historyType + "'  class='hrefPageHistorySpan'>" + i + "</SPAN>"; 

    }
    pages.innerHTML = htmlText;

    makeAJAXCall(sUrl+'?page='+page+'&tim='+d.getTime());
}

//Display Users information
function getUsers(id)
{	
//    displayVisible(getelementbyid('errMsg'), false);
//    displayVisible(getelementbyid('selWorkContactsError'), false);

    displayVisible(getelementbyid('mainWindowPastConference'), false);    
    displayVisible(getelementbyid('mainWindowActiveConference'), false);        

    if(id == 0)
    {
		if(newConf.length == 0 || newConf[newConf.length-1] != 2) newConf[newConf.length] = 2;
        document.title = 'View Users';
        displayVisible(getelementbyid('mainWindowAccount'), false);
        getelementbyid('titleName').innerHTML = 'Users';
        displayVisible(getelementbyid('mainWindowUsers'), true);
    }
    else
    {
        if(id == userid)
        {
			if(newConf.length == 0 || newConf[newConf.length-1] != 1) newConf[newConf.length] = 1;
            myAccount = true;
            document.title = 'Edit My Account';
            getelementbyid('titleName').innerHTML = 'My Account';
            displayVisible(getelementbyid('oldPasswordTR'), true);
        }
        else
        {
			accNames[accNames.length] = id;
			if(newConf.length == 0 || newConf[newConf.length-1] != 3) newConf[newConf.length] = 3;
            myAccount = false;            
            displayVisible(getelementbyid('oldPasswordTR'), false);
        }

        getelementbyid('oldpsw').value = '';
        getelementbyid('newpsw').value = '';
        getelementbyid('repeatpsw').value = '';

        getelementbyid('idd').value = id;
        displayVisible(getelementbyid('mainWindowAccount'), true);
        displayVisible(getelementbyid('mainWindowUsers'), false);
    }

    sUrl = "UsersServlet";
    var d = new Date();


  //alert(newConf);	
    makeAJAXCall(sUrl+'?id=' + id + '&tim='+d.getTime());
}
