//
// $Id: live_help.js 2742 2007-03-02 15:00:16Z zeke $
//

lh_debug = false;

d = document;

function lh_window_onload()
{
	lh_counter = 0;
	lh_first = true;
	lh_invited = false;
	lh_start_chat = false;
	lh_operator_status = -1;
	lh_sendRequest();
	lh_enableLinks(true);
}
onload_handlers.push("lh_window_onload()");


function lh_enableLinks(enable)
{
	var links = ['lh_start_chat_link', 'lh_leave_message_link', 'lh_status_image_link'];
	var hrefs = ["javascript:lh_startChat()", "javascript:lh_leaveMessage()", "javascript:lh_startChat()"];
	
	for (var n in links) {
		var a = d.getElementById(links[n]);
		if (!a) {
			continue;
		}
		
		if (enable) {
			var href = hrefs[n];
		} else {
			var href = "javascript:void(0)";
		}
		
		if (a.setAttribute) {
			a.setAttribute('href', href);
		} else {
			a.href = href;
		}
	}
}


function lh_startTimer()
{
	if (window.lh_timer) {
		clearTimeout(lh_timer);
	}
	lh_timer = setTimeout("lh_sendRequest()", 3000);
}


function __paramsToString(params)
{
	var params_list = [];
	for (key in params) {
		params_list[params_list.length] = key + "=" + escape(params[key].toString());
	}
	var params_string = params_list.join('&');
	
	return params_string;
}


function lh_sendRequest(force, value)
{
	if (force == undefined) {
		force = '';
	}
	
	lh_req = false;
	if (window.XMLHttpRequest) {
		lh_req = new XMLHttpRequest();
	} else {
		lh_req = new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	if (!lh_req) {
		return;
	}
	
	if (lh_first) {
		params = {
			first: 1,
			title: d.title,
			href: location.href,
			browser: lh_BrowserInfo.browser + ", " + lh_BrowserInfo.version,
			os: lh_BrowserInfo.os,
			referer: d.referrer
		}
		lh_first = false;
	} else {
		params = {
			update: 1
		}
	}
	if (lh_counter % 3 == 0 || force == 'stats') {
		params.stats = 1;
	}
	if (lh_invited) {
		params.invited = 1;
	}
	if (force == 'accept') {
		var today = new Date();
		params.local_time = Math.round(today.getTime() / 1000);
		params.user_name = user_name;
		params.invitation = value;
	}
	if (force == 'decline') {
		params.invitation = '0';
	}
	
	lh_req.open('POST', lh_index_file + "?"+target_name+"=lh_visitor", true);
	lh_req.onreadystatechange = function() {
		if (lh_req && lh_req.readyState == 4 && lh_req.responseText) {
			lh_onResponse(lh_req.responseText);
		}
	}
	lh_req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	lh_req.send(__paramsToString(params));
	
	lh_counter++;
	lh_startTimer();
}


function lh_onResponse(text)
{
	if (!text || text.indexOf('result:') != 0) {
		if (window.lh_timer) {
			clearTimeout(lh_timer);
		}
		lh_onError();
		if (lh_debug) {
			alert(text);
		}
		
		return;
	}
	else {
		var result = text.substring(7).split('&');
	}
	
	for (var a = 0, len = result.length; a < len; a++) {
		var pair = result[a].split('=');
		var param = pair[0];
		var value = pair[1];
		
		if (param == 'op_count') {
			// Total operators count recieved
			var op_count = parseInt(value);
			lh_updateStatus('total', op_count);
			
			if (lh_start_chat) {
				var allow = op_count > 0;
				lh_enterChat(allow);
				lh_start_chat = false;
			}
		} else if (param == 'op_free') {
			// Free operators count recieved
			var op_free = parseInt(value);
			lh_updateStatus('free', op_free);
		} else if (param == 'operator') {
			// Operator applies to visitor
			var operator_id = parseInt(value);
			lh_invited = true;
			lh_showInvitation(operator_id);
		}
	}
}


function lh_updateStatus(param, value)
{
	if (param == 'total') {
		var total_count_element = d.getElementById('lh_total_count');
		if (total_count_element) {
			total_count_element.innerHTML = value;
		}
		
		var status_image_src = 'live_help_offline.gif';
		var status_image_hint = lh_lang['image_offline_hint'];
		var new_status = false;
		if (value > 0) {
			status_image_src = 'live_help_online.gif';
			status_image_hint = lh_lang['image_online_hint'];
			new_status = true;
		}
		var status_image = d.getElementById('lh_status_image');
		if (status_image && new_status != lh_operator_status) {
			if (status_image.setAttribute) {
				status_image.setAttribute('src', lh_status_image_path + status_image_src);
				status_image.setAttribute('title', status_image_hint);
			} else {
				status_image.src = lh_status_image_path + status_image_src;
				status_image.title = status_image_hint;
			}
			status_image.style.display = 'inline';
			lh_operator_status = new_status;
		}
	} else if (param == 'free') {
		var free_count_element = d.getElementById('lh_free_count');
		if (free_count_element)	{
			free_count_element.innerHTML = value;
		}
	}
}


function lh_enterChat(allow, force_enter)
{
	if (allow == undefined) {
		allow = false;
	}
	if (force_enter == undefined) {
		force_enter = false;
	}
		
	if (!allow)	{
		lh_chatbox = window.open(lh_index_file + "?"+target_name+"=lh_leave_message&desc=no_ops", 1000, __getPopupParams());
	} else {
		var get_params = 'chat=1';
		if (force_enter) {
			get_params += '&force=1';
		}
	
		lh_chatbox = window.open(lh_index_file + "?"+target_name+"=lh_main&" + get_params, 1000, __getPopupParams());
	}

	if (!window.lh_chatbox) {
		alert(lh_lang['failed_popup']);
	}
}


function lh_onError()
{
	lh_updateStatus('free', 0);
	var total_count_element = d.getElementById('lh_total_count');
	if (total_count_element) {
		total_count_element.innerHTML = d.getElementById('lh_free_count').innerHTML = lh_lang['not_available'];
	}
	lh_enableLinks(false);
}


function __constructPopupParams(params)
{
	var param_arr = [];
	for (param in params) {
		param_arr[param_arr.length] = param + '=' + params[param];
	}
	
	return param_arr.join(',');
}


function __getPopupParams(overload)
{
	var params = {
		width: 600,
		height: 400,
		status: 'yes',
		resizable: 'yes',
		scrollbars: 'no'
	}
	params.screenX = (screen.width - params.width) / 2;
	params.screenY = (screen.height - params.height) / 2;
	// For Opera
	params.top = params.screenX - 30;
	params.left = params.screenY;
	
	if (overload != undefined) {
		for (var param in overload) {
			params[param] = overload[param];
		}
	}
	
	return __constructPopupParams(params)
}


function lh_leaveMessage()
{
	var params = {
		scrollbars: 'no',
		height: 360
	}
	lh_message_box = window.open(lh_index_file + "?"+target_name+"=lh_leave_message", 1001, __getPopupParams(params));
	if (!window.lh_message_box) {
		alert(lh_lang['failed_popup']);
	}
}


function lh_startChat()
{
	lh_start_chat = true;
	lh_sendRequest('stats');
}


function lh_showInvitation(operator_id)
{
	lh_invitation_span = d.createElement('SPAN');
	var span = lh_invitation_span;
	span.style.display = 'none';
	d.getElementsByTagName('BODY')[0].appendChild(span);
	var href = lh_index_file + "?"+target_name+"=lh_invitation&operator_id=" + operator_id + "&rand=" + Math.random()
	// Span must content some text for IE bug walkaround
	span.innerHTML = "text for IE <s" + "cript></s" + "cript>";
	setTimeout(function() {
		var s = lh_invitation_span.getElementsByTagName('script')[0];
		if (s.setAttribute) {
			s.setAttribute('src', href);
		} else {
			s.src = href;
		}
	}, 10);
}


// Actions toward invitation form after it apearing
function lh_defineInvitation()
{
	fn_show_tag('invitation_dialog_bg', false);
	lh_align_dialog();
	window.onscroll = lh_align_dialog;
	
	focus();
	with (d.getElementById('invitation_name')) {
		focus();
		select();
	}
}


function lh_align_dialog() {
	var dlg = document.getElementById('invitation_dialog_bg');
	var msg = document.getElementById('invitation_dialog_msg');
	
	var wnd_sizes = fn_get_window_sizes();
	
	dlg.style.left = 0;
	dlg.style.top = 0;
	dlg.style.width=wnd_sizes['width'];
	dlg.style.height=wnd_sizes['height'];
	
	msg.style.left = wnd_sizes['offset_x'];
	msg.style.top = wnd_sizes['offset_y'];
	msg.style.width = wnd_sizes['view_width'];
	msg.style.height = wnd_sizes['view_height'];	
}


function lh_invitationSubmit() {
	var invitation_name_input = d.getElementById('invitation_name');
	user_name = invitation_name_input.value;
	if (!user_name) {
		alert(lh_lang['please_input_name']);
		invitation_name_input.focus();
		return false;
	}
	
	var today = new Date();
	var local_time = Math.round(today.getTime() / 1000);
	var operator_id = d.forms['invitation_form'].elements['operator_id'].value;
	
	var dummy_frame = d.getElementById('dummy_frame');
	dummy_frame.src = lh_index_file + "?"+target_name+"=lh_visitor" + "&invitation=" + operator_id + "&user_name=" + user_name + "&local_time=" + local_time;
	//lh_sendRequest('accept', operator_id);
	
	lh_invited = false;
	lh_enterChat(true, true);
	
	var lh_div = d.getElementById('lh_div');
	lh_div.parentNode.removeChild(lh_div);
	
	return false;
}


function lh_invitationReset() {
	lh_sendRequest('decline');
	
	lh_invited = false;
	onscroll = '';
	var lh_div = d.getElementById('lh_div');
	lh_div.parentNode.removeChild(lh_div);
	
	return false;
}
