/*
 * $Id: assistant.js,v 1.19 2008-11-26 04:39:27 ramas Exp $
 */

var account = 'test';
var base = 'http://assistant.progstudio.lt/';
var proxy_base = 'webassistant.php?file=';

/*
 * Funkcija sukurianti AJAX objekta bendradarbiavimui
 */
function get_http_request() {
    var http_request = false;
    if (window.XMLHttpRequest) {
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
        }
    } else if (window.ActiveXObject) {
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }
    if (!http_request) {
        alert('Jūs naudojatės per sena naršyklės versija. Jums reiktų ją atsinaujinti.');
    }
    return http_request;
}

// Nustatomi cookiai
function Set_Cookie( name, value, expires, path, domain, secure ) {
    // set time, it\'s in milliseconds
    var today = new Date();
    today.setTime( today.getTime() );

    /*
    if the expires variable is set, make the correct 
    expires time, the current script below will set 
    it for x number of days, to make it for hours, 
    delete * 24, for minutes, delete * 60 * 24
    */
    if ( expires )
    {
    expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date( today.getTime() + (expires) );

    document.cookie = name + "=" +escape( value ) +
    ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
    ( ( path ) ? ";path=" + path : "" ) + 
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
}

// Gaunamas cookis
function Get_Cookie( check_name ) {
	// first we\'ll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

// Web assistant

/*
 * Siunčiame informaciją apie tai, kokiame puslapyje esame
 */
function sendInfo() {
    var http_request = get_http_request();
    http_request.onreadystatechange = function() { 
        track_response(http_request); 
    };
    var url = "track.php?account=" + account + '&url='
        + escape(document.location.href) + '&referrer=' 
        + escape(document.referrer) + '&title=' + escape(document.title);
    var code = account + '_visitor';
    var visitor = Get_Cookie(code);
    if (visitor != null) {
        url = url + '&visitor=' + visitor;
    }
    var url = proxy_base + escape(url);
    http_request.open('GET', url, true);
    http_request.send(null);
}

function track_response(http_request) {
    if (http_request.readyState == 4) {
        if (http_request.status == 200) {
            //alert(http_request.responseText);
            var xmldoc = null;
            if (window.ActiveXObject) {
                // Stupid IE bugfix
                xmldoc = new ActiveXObject("Microsoft.XMLDOM");
                xmldoc.loadXML(http_request.responseText);
            } else {
                xmldoc = http_request.responseXML;
            }
            var visitor = xmldoc.getElementsByTagName('visitor');
            visitor = visitor.item(0).firstChild.data;
            var code = account + '_visitor';
            Set_Cookie(code, visitor, 100, '', '', '');
            show_online_chat();
            check_status();
        } else {
            //alert('There was a problem with the request.');
        }
    }
}

function show_online_chat() {
    var el = document.getElementById('chatbox');
    var html = '<div style="margin:2px;"><table width="296"><tr><td>Online chat</td><td align="right"><a href="#" onclick="return closeChat();">Close</a></td></tr></table><div id="scrollbox" style="border-top:1px solid #4949ff; height: 150px; overflow:auto;"><div id="chattxt"></div></div><form style="margin:0; padding:0;" action="?" method="POST" onsubmit="return sendMsg();"><input type="text" id="inputtxt" style="width:230px;"/><input type="submit" value="Send" style="width:60px;" onclick="return sendMsg();"/></form></div>';
    el.innerHTML = html;
    el.style.display = 'none';
    el.style.width = '300px';
    el.style.height = '200px';
    el.style.position = 'absolute';
    el.style.background = "URL('" + base + 'img/bg.png' + "')";
    el.style.backgroundRepeat = 'no-repeat';
    setTimeout("change_position()", 1000);
    window.onscroll = function() {change_position();}
}

function closeChat() {
    var el = document.getElementById('chatbox');
    el.style.display = 'none';
    var http_request = get_http_request();
    var url = "close_chat.php?account=" + account;
    var code = account + '_visitor';
    var visitor = Get_Cookie(code);
    if (visitor != null) {
        url = url + '&visitor=' + visitor;
    }
    var url = proxy_base + escape(url);
    http_request.open('GET', url, true);
    http_request.send(null);
    return false;
}

function sendMsg() {
    var el = document.getElementById('inputtxt');
    var msg = el.value;
    el.value = '';
    var http_request = get_http_request();
    var url = "send_msg.php?account=" + account + "&msg=" + escape(msg);
    var code = account + '_visitor';
    var visitor = Get_Cookie(code);
    if (visitor != null) {
        url = url + '&visitor=' + visitor;
    }
    var url = proxy_base + escape(url);
    http_request.open('GET', url, true);
    http_request.send(null);
    return false;
}

function change_position() {
    var el = document.getElementById('chatbox');
    var top = top = parseInt(document.documentElement.clientHeight) - 202 
            + parseInt(document.documentElement.scrollTop);
    var left = 0;
    if (window.ActiveXObject) {
        // IE
        left = parseInt(document.documentElement.offsetWidth) - 302 - 20;
    } else {
        left = parseInt(document.documentElement.offsetWidth) - 302;
    }
    el.style.left = left + 'px';
    el.style.top = top + 'px';
}

function check_status() {
    var http_request = get_http_request();
    http_request.onreadystatechange = function() { 
        check_status_response(http_request); 
    };
    var url = "check_status.php?account=" + account;
    var code = account + '_visitor';
    var visitor = Get_Cookie(code);
    if (visitor != null) {
        url = url + '&visitor=' + visitor;
    }
    var url = proxy_base + escape(url);
    http_request.open('GET', url, true);
    http_request.send(null);
}

function check_status_response(http_request) {
    if (http_request.readyState == 4) {
        if (http_request.status == 200) {
            //alert(http_request.responseText);
            var xmldoc = null;
            if (window.ActiveXObject) {
                // Stupid IE bugfix
                xmldoc = new ActiveXObject("Microsoft.XMLDOM");
                xmldoc.loadXML(http_request.responseText);
            } else {
                xmldoc = http_request.responseXML;
            }
            var content = xmldoc.getElementsByTagName('content');
            content = content.item(0).firstChild.data;
            var open = xmldoc.getElementsByTagName('open');
            open = parseInt(open.item(0).firstChild.data);
            var chatbox = document.getElementById('chatbox');
            if (open == 1) {
                chatbox.style.display = '';
                change_position();
            }
            var el = document.getElementById('chattxt');
            el.innerHTML = content + '<div style="height:5px;">&nbsp;</div>';
            var scrollbox = document.getElementById('scrollbox');
            scrollbox.scrollTop = parseInt(el.offsetHeight) - 150;
            if (chatbox.style.display == '') {
                setTimeout("check_status();", 1000);
            } else {
                setTimeout("check_status();", 5000);
            }
        } else {
            //alert('There was a problem with the request.');
        }
    }
}

/*
# vim: expandtab ts=4 sw=4 sts=4
# vim: encoding=utf-8
# vim: fileencoding=utf-8
*/

