//Global variables
var timeID;
var forumTimeID;
var tikkerRefreshRate = 4000; // one second by default it was two seconds
var rand = Math.random();
//var userQue;
var tikkerIsFirefox;
var tikkerIsIE;
var forumIsFirefox;
var forumIsIE;
var i;
//var XmlHttp;
var AjaxServerPageName;
AjaxServerPageName = "ChatService.aspx";

//Creating and setting the instance of appropriate XMLHTTP Request object to a “XmlHttp” variable  
function tikkerGetAjax()
{
	var XmlHttpTikker;
	
	//Creating object of XMLHTTP in IE
	try
	{
		XmlHttpTikker = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e)
	{
		try
		{
			XmlHttpTikker = new ActiveXObject("Microsoft.XMLHTTP");
		} 
		catch(oc)
		{
			XmlHttpTikker = null;
			
		}
	}
	//Creating object of XMLHTTP in Mozilla and Safari 
	if(!XmlHttpTikker && typeof XMLHttpRequest != "undefined") 
	{
		XmlHttpTikker = new XMLHttpRequest();
		
	}
	
	return XmlHttpTikker;
}

// Get browser type
function tikkerSniffBrowserType() {

	tikkerIsFirefox = ( navigator.appName == "Netscape" );
	tikkerIsIE = (navigator.appName == "Microsoft Internet Explorer" );
}
// Start the update timer
function tikkerSetTimers(goBack, UID) {
    timeID = window.setTimeout("tikkerUpdateAll('" + goBack + "','" + UID + "')", tikkerRefreshRate);
}
// Start to update and reset the update timer
function tikkerUpdateAll(goBack, UID) {
    window.clearTimeout(timeID);
    if (i == 0) {
        GetChatRequest(goBack, UID);
        i = 1;
    }
    else if (i == 1) {
        tikkerGetLoggedInUsers(goBack);
        i = 2;
    }
    else {
        tikkerGetActiveUsers(goBack, UID);
        i = 0;
    }
    tikkerSetTimers(goBack, UID);
}
function tikkerReplaceAll(fullString, target, replacement) {
    intIndexOfMatch = fullString.indexOf(target);
    while (intIndexOfMatch != -1) {
        fullString = fullString.replace(target, replacement);
        intIndexOfMatch = fullString.indexOf(target);
    }
    return fullString;
}

//************************Get Active Users(START)***********************
var getActiveUsersId;
function InvokeGetActiveUsers(goBack, UID, delay) {
    getActiveUsersId = window.setTimeout("PingGetActiveUsers('" + goBack + "','" + UID + "'," + delay + ")", delay);
}

function PingGetActiveUsers(goBack, UID, delay) {
    window.clearTimeout(getActiveUsersId);
    tikkerGetActiveUsers(goBack, UID);
    InvokeGetActiveUsers(goBack, UID, delay);
}
function tikkerGetActiveUsers(goBack,UID)
{
    rand++;    
	url = goBack+'?action=UserList&session=' + rand+'&UID='+UID;	
	req = tikkerGetAjax();
	req.onreadystatechange = function() {
	    if (req.readyState == 4 && req.status == 200) {

	        var str = req.responseText;

	        //			str = tikkerReplaceAll(str,"<li>","");
	        //			str = tikkerReplaceAll(str,"</li>"," ");
	        var strforum = str;
	        strforum = tikkerReplaceAll(strforum, "style='cursor:hand'", "");
	        strforum = tikkerReplaceAll(strforum, "onclick=", "");
	        strforum = tikkerReplaceAll(strforum, "images/MessengerSkins/MembersBullet.gif", "images/spacer.gif");
	        var obj = document.getElementById("tikkerUserslist")
	        if (obj != null) {
	            if(str.length>2500)
                    obj.innerHTML = str;
            }
	    }
	}	
	req.open( 'GET', url, true );
	req.send( null );
}
//************************Get Active Users(END)***********************
//************************Get Client Active Users(START)***********************
var getClientActiveUsersId;
function InvokeGetClientActiveUsers(goBack, UID, listContainer, linkContainer, linkString, delay) {
    getClientActiveUsersId = window.setTimeout("PingGetClientActiveUsers('" + goBack + "','" + UID + "','" + listContainer + "','" + linkContainer + "','" + linkString + "'," + delay + ")", delay);
}

function PingGetClientActiveUsers(goBack, UID, listContainer, linkContainer, linkString, delay) {
    window.clearTimeout(getClientActiveUsersId);
    tikkerGetClientActiveUsers(goBack, UID, listContainer, linkContainer, linkString);
    InvokeGetClientActiveUsers(goBack, UID, listContainer, linkContainer, linkString, delay);
}
function tikkerGetClientActiveUsers(goBack, UID, listContainer, linkContainer, linkString) {
    rand++;
    url = goBack + '?action=ClientUserList&session=' + rand + '&UID=' + UID;
    req = tikkerGetAjax();

    req.onreadystatechange = function() {
        if (req.readyState == 4 && req.status == 200) {
            try {
                var usersList = req.responseText.split('~|~')[0];
                var totalOnlineUsers = req.responseText.split('~|~')[1];
                var list = document.getElementById(listContainer);
                var link = document.getElementById(linkContainer);
                if (list != null) {
                    link.innerHTML = linkString + totalOnlineUsers + ')';
                    if (usersList != '') {
                        list.innerHTML = usersList;
                        //list.style.display = 'block';
                    }
                    else {
                        list.innerHTML = '';
                        list.style.display = 'none';
                    }
                }
            }
            catch (e) { alert(e); }
        }
    }
    req.open('GET', url, true);
    req.send(null);
}
//************************Get Client Active Users(END)***********************

//************************Get All Active Users(START)***********************
var getAllActiveUsersId;
function InvokeGetAllActiveUsers(goBack, delay) {
    getAllActiveUsersId = window.setTimeout("PingGetAllActiveUsers('" + goBack + "'," + delay + ")", delay);
}

function PingGetAllActiveUsers(goBack, delay) {
    window.clearTimeout(getAllActiveUsersId);
    tikkerGetAllActiveUsers(goBack);
    InvokeGetAllActiveUsers(goBack, delay);
}
function tikkerGetAllActiveUsers(goBack) {
    rand++;
    url = goBack + '?action=AdminUserList&session=' + rand;
    req = tikkerGetAjax();
    req.onreadystatechange = function() {
        if (req.readyState == 4 && req.status == 200) {
            try {

                var usersList = req.responseText.split('~|~')[0];
                var totalOnlineUsers = req.responseText.split('~|~')[1];

                if (document.getElementById('OnlineUserslist') != null) {

                    if (usersList != '') {
                        document.getElementById('OnlineUserslist').innerHTML = 'Total Online Users:' + totalOnlineUsers + '<br/>' + usersList;
                    }
                }
            }
            catch (e) { alert(e); }
        }
    }
    req.open('GET', url, true);
    req.send(null);
}
//************************Get All Active Users(END)***********************
//**********************Logged In Users(START)************************
var getLoggedInUsersTimeId;
function InvokeGetLoggedInUsers(goBack, delay) {
    getLoggedInUsersTimeId = window.setTimeout("PingGetLoggedInUsers('" + goBack + "'," + delay + ")", delay);
}

function PingGetLoggedInUsers(goBack, delay) {
    window.clearTimeout(getLoggedInUsersTimeId);
    tikkerGetLoggedInUsers(goBack);
    InvokeGetLoggedInUsers(goBack, delay);
}
function tikkerGetLoggedInUsers(goBack)
{
    rand++;
	url = goBack+'?action=LoggedInUserList&session=' + rand;	
	req = tikkerGetAjax();
	req.onreadystatechange = function(){	
		if( req.readyState == 4 && req.status == 200 ) {
			
			var str = req.responseText;
			
			str = tikkerReplaceAll(str,"<li>","");
			str = tikkerReplaceAll(str,"</li>"," ");
			var strforum =  str;		
			strforum = tikkerReplaceAll(strforum,"style='cursor:hand'","");
			strforum = tikkerReplaceAll(strforum,"onclick=","");
			strforum = tikkerReplaceAll(strforum,"images/MessengerSkins/MembersBullet.gif","images/spacer.gif");
            var obj = document.getElementById("LoggedInUsersList")
		   
		    if(obj!=null)
		    {
		        obj.innerHTML ="[ <b>Total Active Members: </b> ] " + str;
		    }
		}	
	}	
	req.open( 'GET', url, true );
	req.send( null );
}

//**********************Logged In Users(END)************************
//************************Chat Request Processing(START)************************/
var getRequestTimeId;
function InvokeGetChatRequest(goBack, UID, delay) {
    getRequestTimeId = window.setTimeout("PingGetChatRequest('" + goBack + "','" + UID + "'," + delay + ")", delay);
}

function PingGetChatRequest(goBack, UID, delay) {
    window.clearTimeout(getRequestTimeId);
    GetChatRequest(goBack, UID);
    InvokeGetChatRequest(goBack, UID, delay);
}

function GetChatRequest(goBack,UID)
{
    rand++;    
	url = goBack + '?action=GetChatRequest&UID=' + UID + '&session=' + rand;	
	req = tikkerGetAjax();

	req.onreadystatechange = function() {
	    if (req.readyState == 4 && req.status == 200) {

	        var objTikkerMessage = document.getElementById("tikkerMessage");

	        if (objTikkerMessage != null) {
	            if (req.responseText == '') {
	                //objTikkerMessage.innerHTML =req.responseText;
	            }
	            else {
	                try {


	                    userIds = req.responseText.split('~');
	                    //alert(req.responseText);
	                    var reqID = '0';
	                    var targetID = '0';
	                    if (userIds.length > 0) {
	                        if (userIds[0].length > 0)
	                            reqID = userIds[0];
	                    }
	                    if (userIds.length > 1) {
	                        if (userIds[1].length > 0)
	                            targetID = userIds[1];
	                    }	                    
	                    if (targetID != '0') {
	                        OpenWindow(reqID, true);
	                        /*****Conversation Status
	                        Initiate:0,
	                        Inprocess:1,
	                        Over:2
	                        ************************/
	                        ChangeConversationStatus(ServerUrl, reqID, targetID, 1);
	                    }
	                }
	                catch (e) {
	                }
	            }
	        }
	    }
	}	
	req.open( 'GET', url, true );
	req.send( null );
}
function PostChatRequest(goBack, UID, TUID) {
    rand++;
    url = ServerUrl + '?action=PostChatRequest&UID=' + UID + '&TUID=' + TUID + '&session=' + rand;
    req = tikkerGetAjax();
    req.onreadystatechange = function() {
        if (req.readyState == 4 && req.status == 200) {
        }
    }
    req.open('GET', url, true);
    req.send(null);
}
function RemoveChatRequest(goBack, UID, TUID) {
    rand++;
    url = ServerUrl + '?action=RemoveChatRequest&UID=' + UID + '&TUID=' + TUID + '&session=' + rand;
    req = tikkerGetAjax();
    req.onreadystatechange = function() {
        if (req.readyState == 4 && req.status == 200) {
        }
    }
    req.open('GET', url, true);
    req.send(null);
}
function ChangeConversationStatus(goBack, UID, TUID, status) {
    rand++;
    url = goBack + '?action=ChangeConversationStatus&UID=' + UID + '&TUID=' + TUID + '&Status='+ status +'&session=' + rand;
    req = tikkerGetAjax();
    req.onreadystatechange = function() {
        if (req.readyState == 4 && req.status == 200) {

        }
    }
    req.open('GET', url, true);
    req.send(null);
}
/************************Chat Request Processing(END)************************/
/****************Chat Request Information Processing(START)******************/
function PostChatInfo(UID, TUID, OtherInfo) {
    rand++;
    url = ServerUrl + '?action=PostChatInfo&UID=' + UID + '&TUID=' + TUID + '&OtherInfo=' + OtherInfo + '&session=' + rand;
    req = tikkerGetAjax();
    req.onreadystatechange = function() {
        if (req.readyState == 4 && req.status == 200) {
        }
    }
    req.open('GET', url, true);
    req.send(null);
}
function GetChatInfo(goBack, UID,TUID) {    
    rand++;
    url = goBack + '?action=GetChatInfo&UID=' + UID + '&TUID=' + TUID + '&session=' + rand;    
    req = tikkerGetAjax();
    req.onreadystatechange = function() {
        if (req.readyState == 4 && req.status == 200) {

            var objOtherInfo = document.getElementById("otherInfo");

            if (objOtherInfo != null && req.responseText != '') {

                params = req.responseText.split('<head');
                objOtherInfo.innerHTML = params[0];
            }
        }
    }
    req.open('GET', url, true);
    req.send(null);    
}
/****************Chat Request Information Processing(END)******************/
/*********************Start Change User Status*********************/
function ChangeUserStatus(UID, status) {
    rand++;
    url = ServerUrl + '?action=ChangeUserStatus&UID=' + UID + '&Status=' + status + '&session=' + rand;
    req = tikkerGetAjax();
    req.onreadystatechange = function() {
        if (req.readyState == 4 && req.status == 200) {

        }
    }
    req.open('GET', url, true);
    req.send(null);
}
/**********************End Change User Status**********************/
function TotalOnlineUsersByUserId(UID) {
    rand++;
    url = ServerUrl + '?action=GetTotalOnlineUsersByUserId&UID=' + UID + '&session=' + rand;
    req = tikkerGetAjax();
    req.onreadystatechange = function() {
        if (req.readyState == 4 && req.status == 200) {
            //            var totalUsers = req.responseText.split('|~|');
            //            alert(totalUsers.length);
            //            if (totalUsers.length >= 3) {
            //alert(req.responseText);
            //document.getElementById('messengerLink').innerHTML = req.responseText;  //'Messenger - ' + totalUsers[1];
            //            }
        }
    }
    req.open('GET', url, true);
    req.send(null);
}

function getDateTime() {
    var a_p = "";
    var d = new Date();

    var curr_hour = d.getHours();

    if (curr_hour < 12) {
        a_p = "AM";
    }
    else {
        a_p = "PM";
    }
    if (curr_hour == 0) {
        curr_hour = 12;
    }
    if (curr_hour > 12) {
        curr_hour = curr_hour - 12;
    }

    var curr_min = d.getMinutes();

    var time = curr_hour + " : " + curr_min + " : " + d.getSeconds() + " " + a_p;
    var m_names = new Array("January", "February", "March","April", "May", "June", "July", "August", "September","October", "November", "December");
    var curr_date = d.getDate();
    var curr_month = d.getMonth();
    var curr_year = d.getFullYear();
    var fullDate = curr_date + "-" + m_names[curr_month] + "-" + curr_year + " " + time;
    return fullDate;
}
function GetTimeZone() {
    var rightNow = new Date();
    var jan1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);  // jan 1st
    var june1 = new Date(rightNow.getFullYear(), 6, 1, 0, 0, 0, 0); // june 1st
    var temp = jan1.toGMTString();
    var jan2 = new Date(temp.substring(0, temp.lastIndexOf(" ") - 1));
    temp = june1.toGMTString();
    var june2 = new Date(temp.substring(0, temp.lastIndexOf(" ") - 1));
    var std_time_offset = (jan1 - jan2) / (1000 * 60 * 60);
    var daylight_time_offset = (june1 - june2) / (1000 * 60 * 60);
    var dst;
    if (std_time_offset == daylight_time_offset) {
        dst = 0; // daylight savings time is NOT observed
    } else {
        // positive is southern, negative is northern hemisphere
        var hemisphere = std_time_offset - daylight_time_offset;
        if (hemisphere >= 0)
            std_time_offset = daylight_time_offset;
        dst = 1; // daylight savings time is observed
    }
    //var i;
    // check just to avoid error messages
    //	if (document.getElementById('timezone')) {
    //		for (i = 0; i < document.getElementById('timezone').options.length; i++) {
    //			if (document.getElementById('timezone').options[i].value == convert(std_time_offset)+","+dst) {
    //				document.getElementById('timezone').selectedIndex = i;
    //				break;
    //			}
    //		}
    //	}
    return std_time_offset+dst;
}


function pausecomp(millis) {
    var date = new Date();
    var curDate = null;

    do { curDate = new Date(); }
    while (curDate - date < millis);
}
//*******************Online Users Ping********************//
var getOnlineUserTimeId;
function InvokeOnlineUserPing(serviceUrl ,UID, delay) {
    getOnlineUserTimeId = window.setTimeout("SetOnlineUserPing('" + serviceUrl + "','" + UID + "'," + delay + ")", delay);    
}

function SetOnlineUserPing(serviceUrl, UID, delay) {
    window.clearTimeout(getOnlineUserTimeId);
    PostOnlineUserPing(serviceUrl, UID);
    InvokeOnlineUserPing(serviceUrl, UID, delay);
}
function PostOnlineUserPing(serviceUrl, UID) {
    rand++;
    url = serviceUrl + '?action=PostOnlineUserPing&UID=' + UID + '&session=' + rand;
    req = tikkerGetAjax();
    req.onreadystatechange = function() {
        if (req.readyState == 4 && req.status == 200) {
        }
    }
    req.open('GET', url, true);
    req.send(null);
}

//************************Get Contact Add Requests***************************//
var getContactRequestTimeId;
function InvokeGetContactRequest(goBack, UID, delay) {
    getContactRequestTimeId = window.setTimeout("PingGetContactRequest('" + goBack + "','" + UID + "'," + delay + ")", delay);
}

function PingGetContactRequest(goBack, UID, delay) {
    window.clearTimeout(getContactRequestTimeId);
    GetContactRequest(goBack, UID);
    InvokeGetContactRequest(goBack, UID, delay);
}

function GetContactRequest(goBack, UID) {
    rand++;
    url = goBack + '?action=GetContactRequest&UID=' + UID + '&session=' + rand;
    req = tikkerGetAjax();

    req.onreadystatechange = function() {
        if (req.readyState == 4 && req.status == 200) {
            try {
                contactInfo = req.responseText.split('~');
                var contactID = 0;
                var contactName = '';
                if (contactInfo.length > 0) {
                    if (contactInfo[0].length > 0)
                        contactID = parseInt(contactInfo[0], 10);
                }
                if (contactInfo.length > 1) {
                    if (contactInfo[1].length > 0)
                        contactName = contactInfo[1];
                }
                if (contactID > 0) {

                    /*******Status**********  
                    Pending:0; 
                    InProcess:1; 
                    Accepted:2; 
                    Blocked:3; 
                    Deleted/Rejected:4 
                    ***********************/                   
                    if (isNaN(contactName)) {                        
                        var contactMessage = ' ' + contactName + ' would like to add you to his or her \r\n Messenger List. Do you want to allow this person to add you into contact list?';
                        if (UserType == 7)
                            contactMessage = ' Customer ' + contactName + ' would like to enquire about a car. Do you want to allow this person to add you into contact list?';
                        if (confirm(contactMessage)) {
                            ProcessContactRequest(goBack, contactID, 2); //Accepted
                        }
                        else
                            ProcessContactRequest(goBack, contactID, 4); // Deleted/Rejected
                    }
                }
            }
            catch (e) {
            }
        }
    }
    req.open('GET', url, true);
    req.send(null);
}
function ProcessContactRequest(goBack, contactId,status) {
    rand++;
    url = goBack + '?action=SetContactRequest&ContactID=' + contactId + '&Status=' + status + ' &session=' + rand;
    req = tikkerGetAjax();
    req.onreadystatechange = function() {
        if (req.readyState == 4 && req.status == 200) {
        }
    }
    req.open('GET', url, true);
    req.send(null);
}
function HasPopupBlocked(poppedWindow) {
    var result = false;

    try {
        if (typeof poppedWindow == 'undefined') {
            // Safari with popup blocker... leaves the popup window handle undefined
            result = true;
        }
        else if (poppedWindow && poppedWindow.closed) {
            // This happens if the user opens and closes the client window...
            // Confusing because the handle is still available, but it's in a "closed" state.
            // We're not saying that the window is not being blocked, we're just saying
            // that the window has been closed before the test could be run.
            result = false;
        }
    } catch (err) {
        //if (console) {
        //    console.warn("Could not access popup window", err);
        //}
    }

    return result;
}

