
function get_client_os()
{
	switch (navigator.platform.toLowerCase()) {
	case "win32":
	case "windows":
		return "win";
	case "mac68k":
	case "macppc":
		return "mac";
	case "linux i686":
		return "nix";
	default:
		return "wce";
		return "sbi";
	}
}

function get_client_agent()
{
	var agent = navigator.userAgent.toLowerCase();
	if (agent.indexOf("opera") > -1)
		return "opera";
	if (agent.indexOf("konqueror") > -1)
		return "konqueror";
	if (agent.indexOf("safari") > -1)
		return "safari";
	if (agent.indexOf("msie") > -1)
		return "ie";
	else
		return "mozilla";
}

function get_client_agent_version()
{
	var agent = navigator.userAgent.toLowerCase();
}

function get_client_language()
{
	if (navigator.appName == 'Netscape')
		detect_lang = navigator.language;
	else
		detect_lang = navigator.browserLanguage;

	if (detect_lang.toLowerCase().indexOf('cn') > -1)
		_lang = "zh-CN";
	else if (detect_lang.toLowerCase().indexOf('tw') > -1)
		_lang = "zh-TW";
	else
		_lang = "en";
		
	return _lang;
}

function showWait(str) {
	window.status = str;
	$("msgtd").innerHTML = str;

	$("acttd").width = '1px';
	$("acttd").style.display = 'none';
	$("msgtd").width = '100%';
	$("msgtd").style.display = 'block';
}

function closeWait() {
	window.status = '';

	$("msgtd").width = '1px';
	$("msgtd").style.display = 'none';
	$("acttd").width = '100%';
	$("acttd").style.display = 'block';
}

function download_finished(obj) {
	try {
		if (obj.version != null) {
			closeWait();
			return;
		}
	} catch (err) { }
	download_failed();
}

function pick_publisher()
{
	var publisher;
	var xx = location.pathname.split("/");
	if (xx[1] == "_")
		publisher = "localhost";
	else
		publisher = unescape(xx[1]);
	return publisher;
}

var xmlHttp;
function createXMLHttpRequest() {
	if (window.ActiveXObject) {
		xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	} else if (window.XMLHttpRequest) {
		xmlHttp = new XMLHttpRequest();
	}
}

var first = true;
function handleStateChange() {
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
			if (first) {
				first = false;
				parseResult();
			}
		} else if (xmlHttp.status == 503) {
			showWait(txt_notsupported);
		}
	}
}

function mozilla_resize()
{
//	$("acttd").style.width = "100%";
//	$("acttd").style.height = "100%";
}

function activex_install(code)
{
	var result = xmlHttp.responseXML;
	var object = result.getElementsByTagName("object")[0];
	var _package = result.getElementsByTagName("package")[0];
	var param = result.getElementsByTagName("param")[0];

	var html = "<OBJECT id=uudral style='width:100%;height:100%'"
		+ " classid=" + object.getElementsByTagName("classid")[0].firstChild.nodeValue
		+ " codebase=" + object.getElementsByTagName("codebase")[0].firstChild.nodeValue
		+ "#version=" + object.getElementsByTagName("version")[0].firstChild.nodeValue.replace(/\./g, ",")
		+ " onreadystatechange='javascript:download_finished(this);'>"
		+ "<PARAM name=pkgversion value=" + _package.getElementsByTagName("version")[0].firstChild.nodeValue + ">\n"
		+ "<PARAM name=pkgcodebase value=" + _package.getElementsByTagName("codebase")[0].firstChild.nodeValue + ">\n"
		+ "<PARAM name=version value=" + param.getElementsByTagName("version")[0].firstChild.nodeValue + ">\n"
		+ "<PARAM name=service value=" + param.getElementsByTagName("service")[0].firstChild.nodeValue + ">\n"
		+ "<PARAM name=LogLevel value=" + param.getElementsByTagName("loglevel")[0].firstChild.nodeValue + ">\n"
		+ "<PARAM name=Cipher value='" + param.getElementsByTagName("cipher")[0].firstChild.nodeValue + "'>\n"
		+ "<PARAM name=Digest value='" + param.getElementsByTagName("digest")[0].firstChild.nodeValue + "'>\n"
		+ "<PARAM name=RootCert value='" + param.getElementsByTagName("rootcert")[0].firstChild.nodeValue + "'>\n";
	if (istar_lang != null) {
		html += "<PARAM name=language value='" + istar_lang + "'>\n";
	}
	
	try {
		var v = param.getElementsByTagName("realms")[0].firstChild.nodeValue;
		html += "<PARAM name=Realms value='" + v + "'>\n";
	} catch (err) { }
	
	try {
		var v = param.getElementsByTagName("secimage")[0].firstChild.nodeValue;
		html += "<PARAM name=SecImage value='" + v + "'>\n";
	} catch (err) { }

	try {
		var v = param.getElementsByTagName("cert")[0].firstChild.nodeValue;
		html += "<PARAM name=Cert value='" + v + "'>\n";
	} catch (err) { }

	try {
		var v = param.getElementsByTagName("relays")[0].firstChild.nodeValue;
		html += "<PARAM name=relays value='" + v + "'>\n";
	} catch (err) { }
	
	try {
		var v = param.getElementsByTagName("account")[0].firstChild.nodeValue;
		html += "<PARAM name=account value='" + v + "'>\n";
	} catch (err) { }

/* for windows mozilla */
	if (get_client_agent() == "mozilla") {
		html += "<PARAM name=Publisher value='" + pick_publisher() + "'>\n";
		html += "<PARAM name=Exchange value='" + location.host + "'>\n";
		html += "<PARAM name=PackageVersion value=" + _package.getElementsByTagName("version")[0].firstChild.nodeValue + ">\n";
//		html += "<PARAM name=Proxy value='HTTP=10.1.16.1:3128;'>\n";
		html += "<PARAM name=Proxy value='" + $('istar_x').version + "'>\n";

		if (code != 0) {
			$("app_div").innerHTML = "";
			$("msg_div").innerHTML = "Package is invalid.";
			return;
		}
		
		window.captureEvents(Event.RESIZE);
		window.onresize = mozilla_resize;
	}
/* for windows mozilla */

	html +=  txt_download_failed + "</OBJECT>";
	$("acttd").innerHTML = html;
}

function parseResult() {
	var result = xmlHttp.responseXML;
	var object = result.getElementsByTagName("object")[0];
	var _package = result.getElementsByTagName("package")[0];
	var param = result.getElementsByTagName("param")[0];

	closeWait();
	switch (get_client_os()) {
	case "win":
		if (get_client_agent() == "ie") {
			activex_install(0);
			break;
		}

/* for windows mozilla */
		_dotver = object.getElementsByTagName("version")[0].firstChild.nodeValue;
		_hexver = istarframe_version();

		$("acttd").style.width = "100%";
		$("acttd").style.height = "100%";
		if (_hexver==null || dot_2_hex(_dotver)>_hexver) {
			var _path = object.getElementsByTagName("codebase")[0].firstChild.nodeValue.replace(/ipkg/, 'iplg');
			istarframe_install(_path + '/win32-x86.cab');
		} else {
			html = "<embed id='istar_x' type='application/istar-plugin'"
				+ " ver='" + _package.getElementsByTagName("version")[0].firstChild.nodeValue + "'"
				+ " src='" + _package.getElementsByTagName("codebase")[0].firstChild.nodeValue + "'"
				+ " hidden=true>";
			html += "<div align=center id='app_div'></div>";
			html += "<div align=center id='msg_div'></div>";
			$("acttd").innerHTML = html;
		}
/* for windows mozilla */
		break;
	case "nix":
		_dotver = object.getElementsByTagName("version")[0].firstChild.nodeValue;
		_hexver = istarframe_version();
		if (_hexver==null || dot_2_hex(_dotver)>_hexver) {
			var _path = object.getElementsByTagName("codebase")[0].firstChild.nodeValue.replace(/ipkg/, 'iplg');
			istarframe_install(_path + '/linux-x86.cab');
		} else {
			var html = "<embed id='istar_x' type='application/x-istar-frame_"+ _hexver.substr(0, 4) +"'"
				+ " ver='" + dot_2_hex(_package.getElementsByTagName("version")[0].firstChild.nodeValue) + "'"
				+ " src='" + _package.getElementsByTagName("codebase")[0].firstChild.nodeValue + "'"
				//+ " src='istarapp.xpi'"
				+ " hidden=true>"
				+ "<div align=center id='app_div'></div>"
				+ "<div align=center id='msg_div'></div>";
			$("acttd").innerHTML = html;
		}
		break;
	}
}

function loadSvcContent(url) {
	showWait(txt_downloading);
	try {
		createXMLHttpRequest();
		xmlHttp.onreadystatechange = handleStateChange;
		xmlHttp.open("GET", url, true);
		xmlHttp.send(null);
	} catch (err) {
		download_failed();
	}
}

/* script for mozilla */
var plugin_name = "ISTAR Plug-in";
function istarframe_version()
{
	if (navigator.plugins) {
		var plugin = navigator.plugins[plugin_name];
		if (plugin)
			return plugin.description;
	}
	return null;
}

function dot_2_hex(dot)
{
	var _hex = "";
	var _dv = dot.split(".");

	for (i=0; i<_dv.length; i++) {
		_number = parseInt(_dv[i]);
		_string = "0" + _number.toString(16);
		_hex += _string.substr(-2, 2);
	}

	return _hex;
}

function xpinstall_callback(url, status)
{
	if(status ==0)
		navigator.plugins.refresh(true);
	else
		$("msg_div").innerHTML = "<a style='cursor:pointer' onclick='install()'>click here to install.</a>";
}

function istarframe_install(_pkg_path)
{
	//xpi={'plugins/XISTARPlugin' : _pkg_path + '/istarframe.xpi'};
	xpi={'plugins/XISTARPlugin' : _pkg_path};
	return InstallTrigger.install(xpi, xpinstall_callback);
}

function istarapp_install(code)
{
	$("app_div").innerHTML = "";
	if (code == 0) {
		$("msg_div").innerHTML = "Install package succeed.";
		istar_connect(xmlHttp.responseText);
	} else
		$("msg_div").innerHTML = "Package is invalid.";
}

function download_process(dsize, tsize)
{
	if (tsize > 0) {
		_dp = "" + (dsize/tsize) * 100;
		//$("msg_div").innerHTML = _ss.substr(0, 5) + "%";
		_ss = "<div align=left style='width:60%; border:solid 1px #000;'>"
		+ "<div style='background:blue; width: "+ (dsize/tsize)*100 +"%; height: 20px;'></div>"
		+ "</div>"
		+ "downloaded "+ _dp.substr(0, 5) +"%";
		$("msg_div").innerHTML = _ss;
	}
}

function $(){
	return document.getElementById(arguments[0]);
}

function login_commit(account_required)
{
	$("user").disabled = true;
	$("pass").disabled = true;
	$("realm").disabled = true;
	$("btn_login").disabled = true;
	$("btn_reset").disabled = true;

	if (account_required == 1) {
		$("account_name").disabled = true;
		$("account_pass").disabled = true;
		$("account_save").disabled = true;
		$("istar_x").call("login", $("user").value, $("realm").value, $("pass").value,
				$("account_name").value, $("account_pass").value,
				$("account_save").checked?"1":"0");
	} else
		$("istar_x").call("login", $("user").value, $("realm").value, $("pass").value);

	$("msg_div").innerHTML = "Authenticating...";
	$("app_div").innerHTML = "";

	document.body.style.cursor = 'wait';
}

function login_reset(account_required)
{
	$("user").value = "";
	$("pass").value = "";
	if (account_required == 1) {
		$("account_name").value = "";
		$("account_pass").value = "";
		$("account_save").checked = false;
	}
}

/* param : 
	realms: realm list
	account_required: account login
	default_realm: default realm
	account_save: save account option
	account_name: account name
	account_pass: account pass
*/
function show_login(realms, account_required)
{
var login_html_header = 
"<style>" +
".tablebd { border: 1px solid #000000; }" +
".inp{width:200px; }" +
"</style>" +
"<table width=360 cellspacing=0>";
var login_html_foot = "</table>";

var login_html_body =
"	<tr>" +
"		<td colspan=2 height=25 bgcolor='#D1D3D4'><b>User Login</b></td>" +
"	</tr>" +
"	<tr><td height='5' colspan='2'></td></tr>";

var publisher_html_body = "<tr><td colspan=2>" +
"<table cellspacing='0' class='tablebd' width='100%'>";

publisher_html_body += 
"	<tr>" +
"		<td width=130 height='33' align='left' style='font-size:9pt'>Publisher:</td>" +
"		<td><input type='text' class='inp' disabled='true' value='"+ pick_publisher() +"'/></td>" +
"	</tr>";

var realm_info =
"	<tr>" +
"		<td height='33' align='left' style='font-size:9pt'>Realm:</td>" +
"		<td><select id='realm' class='inp'>";
for (i=0; i<realms.length; i++)
	realm_info += "<option value=\"" + realms[i] + "\">" + realms[i] + "</option>";
realm_info +=
"		</select></td>" +
"	</tr>";
publisher_html_body += realm_info;

publisher_html_body += 
"	<tr>" +
"		<td height='33' align='left' style='font-size:9pt'>Username:</td>" +
"		<td><input type='text' id='user' class='inp' onload='this.focus();'/></td>" +
"	</tr>" +
"	<tr>" +
"		<td height='33' align='left' style='font-size:9pt'>Password:</td>" +
"		<td><input type='password' id='pass' class='inp'/></td>" +
"	</tr>";

publisher_html_body +=
"</table>" +
"</td></tr>";

login_html_body += publisher_html_body +
"<tr><td colspan=2 height=10>&nbsp;</td></tr>";

var account_html_body = "<tr><td colspan=2>" +
"<table cellspacing='0' class='tablebd' width='100%'>" +
"	<tr>" +
"		<td width=130 height='33' align='left' style='font-size:9pt'>VeriWire Account:</td>" +
"		<td><input type='text' id='account_name' class='inp'/></td>" +
"	</tr>" +
"	<tr>" +
"		<td height='33' align='left' style='font-size:9pt'>VeriWire Password:</td>" +
"		<td><input type='password' id='account_pass' class='inp'/></td>" +
"	</tr>" +
"	<tr>" +
"		<td colspan=2 style='font-size:9pt'>" +
"			<input type='checkbox' id='account_save'></checkbox>" +
"			<label for='account_save'>Save VeriWire account and password</label>" +
"		</td>" +
"	</tr>" +
"</table></td></tr>";

if (account_required == 1)
	login_html_body += account_html_body;

login_html_body += 
"	<tr><td colspan=2 height=5></td></tr>" +
"	<tr height=25>" +
"		<td align='left'>" +
"			<input type=button value='Help'></input>" +
"		</td>" +
"		<td align='right'>" +
"			<input type=button value='Login' id='btn_login'" +
				" onclick='login_commit("+account_required+")'>" +
			"&nbsp;&nbsp;" +
"			<input type=button value='Reset' id='btn_reset'" +
				" onclick='login_reset("+account_required+")'>" +
"		</td>" +
"	</tr>";

	$("msg_div").innerHTML = "";
	$("app_div").innerHTML = login_html_header + login_html_body + login_html_foot;

	if (arguments.length == 3) {
		var params = arguments[2];
		switch (params.length) {
		case 4:
			if (account_required && params[1]==1)
				$('account_pass').value = params[3];
		case 3:
			if (account_required && params[1]==1)
				$('account_name').value = params[2];
		case 2:
			if (account_required)
				$('account_save').checked = params[1];
		case 1:
			for (var i=0; i<$('realm').options.length; i++) {
				if ($('realm').options[i].value != params[0])
					continue;
				$('realm').options[i].selected = true;
				break;
			}
			break;
		}
	}
}

function show_applist(appid, appname, path, param, icon)
{
	document.body.style.cursor = 'default';
	$("msg_div").innerHTML = "";
	var appitem = "<div align='center' style='float:left; width:110; height:70'>" +
			"<img style='cursor:pointer' width=50 height=50 src='data:image;base64,"+ icon +"'" +
			" id='icon_"+ appid +"'" +
			" onDblClick=\"launch_app('"+ appid +"', this)\"" +
			" onClick=\"select_app(this)\"" +
			" onContextMenu=\"select_app(this); return config_app('"+ appid+"', event);\" />" +
			"<br><span>" + appname + "</span>" +
			"<input type=hidden value=\""+ appname +"\" id='name_"+ appid +"'>" +
			"<input type=hidden value=\""+ path +"\" id='path_"+ appid +"'>" +
			"<input type=hidden value=\""+ param +"\" id='param_"+ appid +"'>" +
			"</div>";
	$("app_div").innerHTML += appitem;
}

function show_error(code)
{
	document.body.style.cursor = 'default';
	$("app_div").innerHTML = "";
	switch (-code) {
	case 402:
		$("msg_div").innerHTML = "No applications";
		break;
	case 403:
		$("msg_div").innerHTML = "Authentication failed";
		break;
	case 0x20001001:
		$("msg_div").innerHTML = "System exception [incompatible session parameters]";
		break;
	case 0x20001001:
		$("msg_div").innerHTML = "System exception [cb_transport]";
		break;
	case 0x20001002:
		$("msg_div").innerHTML = "Session negotiation timed out";
		break;
	case 0x20001003:
		$("msg_div").innerHTML = "cb_final_recv";
		break;
	case 0x20001004:
		$("msg_div").innerHTML = "Failed to connect to VeriWire network";
		break;
	case 0x20001005:
		$("msg_div").innerHTML = "System exception [create_sslctx]";
		break;
	case 0x20000007:
		$("msg_div").innerHTML = "Session terminated by the same account logged in at a different location";
		break;
	case 0x20010001:
		$("msg_div").innerHTML = "VeriWire subscriber authentication failed";
		break;
	default:
		$("msg_div").innerHTML = "Lost connection. code = " + code;
		break;
	}
}

function _resume_cursor(_id)
{
	$('icon_'+_id).style.cursor  = 'pointer';
	document.body.style.cursor = 'default';
}

function launch_app(appid)
{
	$('icon_'+appid).style.cursor = 'wait';
	document.body.style.cursor = 'wait';
	$("istar_x").call("launch", appid);
	window.setTimeout(_resume_cursor, 5000, appid);
}

function istar_connect(rappxml)
{
	$("istar_x").call("connect", location.host, pick_publisher(), rappxml);
	//$("istar_x").connect("10.1.77.1", "zgye771@uu200.com", "rapp.xml");
}

function set_app_info(appid)
{
	var _path = $("path_text").value;
	$("path_"+appid).value = _path;
	var _param = $("param_text").value;
	$("param_"+appid).value = _param;
	var _icon = $("icon_text").value;
	$("icon_"+appid).value = _icon;
	$("istar_x").call("setapp", appid, _path, _param, _icon);
}

var g_drag = false;
var g_diffx = 0;
var g_diffy = 0;
function handle_drag_start(e)
{
	g_drag = true;	
	var obj = $("menu_div");
	g_diffx = e.pageX - obj.offsetLeft;
	g_diffy = e.pageY - obj.offsetTop;
}

function handle_drag(e)
{
	if (g_drag == false)
		return;
	var obj = $("menu_div");
	obj.style.left = e.pageX - g_diffx;
	obj.style.top = e.pageY - g_diffy;
}

function handle_drag_stop(e)
{ g_drag = false; }

function create_config_div(appid)
{
var divhtml = "<style>" +
".inp{border:1px solid #84a1bd; width:200px; padding:2px 2px 2px 2px}" +
"</style>";

	divhtml += "<table bgcolor='#FFFFFF' width=100% height=100% border=0 cellspacing=0>" +
		"<tr bgcolor='#C5C5B8'><td colspan=2>" +
			"<div align=left id='title_div' onmousedown=\"handle_drag_start(event);\"" +
			" style='width:300px; height=10px; cursor:move'><b>Config</b></div>" +
		"</td><td width=10>" +
			"<span onclick='hide_menu();' style='cursor:pointer'>X</span>" +
		"</td></tr>" +
		"<tr><td>Application:</td><td>"+ $('name_'+appid).value +"</td><td></td></tr>" +
		"<tr height=30><td>Local Client:</td><td>" +
			"<input type='file' onchange=\"$('path_text').value=this.value;\" style='position:absolute'>" +
			"<input type='text' id='path_text' style='position:absolute'>" +
		"</td><td></td></tr>" +
		"<tr height=30><td>Icon:</td><td>" +
			"<input type='file' onchange=\"$('icon_text').value=this.value;\" style='position:absolute'>" +
			"<input type='text' id='icon_text' style='position:absolute'>" +
		"</td><td></td></tr>" +
		"<tr height=40 valign='bottom'><td>Parameter:</td><td><input type='text' id='param_text'></td><td></td></tr>" +
		"<tr><td></td><td align='right'>" +
			"<input type='button' value='    OK    ' onclick=\"set_app_info('"+ appid +"'); hide_menu();\">" +
			"&nbsp&nbsp<input type='button' value='CANCEL' onclick='hide_menu();'>" +
		"</td><td></td></tr>" +
		"</table>";

	return divhtml;
}

function show_menu(appid, x, y)
{
	var menu_width = 400;
	var menu_height = 200;

	var objdiv = document.createElement("DIV");
	objdiv.id = "menu_div";
	objdiv.style.width = menu_width;
	objdiv.style.height = menu_height;
	objdiv.style.position = 'absolute';
	objdiv.style.background = '#C5C5B8';
	objdiv.style.border = 'solid 1px #000';

	if (x + menu_width > document.body.clientWidth)
		objdiv.style.left = x-menu_width;
	else
		objdiv.style.left = x;
	if (y + menu_height > document.body.clientHeight)
		objdiv.style.top = y-menu_height;
	else
		objdiv.style.top = y;

	objdiv.onmousemove = handle_drag;
	objdiv.onmouseup = handle_drag_stop;

	objdiv.innerHTML = create_config_div(appid);

	document.body.appendChild(objdiv);
	$('path_text').value = $('path_'+appid).value;
	$('param_text').value = $('param_'+appid).value;
}

function hide_menu()
{
	var obj = $("menu_div");
	if (obj == undefined)
		return;
	obj.parentNode.removeChild(obj);
}

function config_app(appid, e)
{
	hide_menu();
	show_menu(appid, e.pageX, e.pageY);
	return false;
}

var selected_app;
function select_app(obj)
{
	if (selected_app!=undefined && obj!=selected_app)
		selected_app.parentNode.childNodes[2].style.background = '#FFFFFF';
	
	selected_app = obj;
	obj.parentNode.childNodes[2].style.background = '#acacac';
	return;
}

/* ajax for rvsweb proxy */
function ajax(method, url, data, onload_call, onsend_call)
{
	var _httpobj;
	var _httpurl;
	
	function createXMLHttpRequest()
	{
		var _xmlhttp = null;
		
		if (window.ActiveXObject) {
			_xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} else if (window.XMLHttpRequest) {
			_xmlhttp = new XMLHttpRequest();
		}
	
		return _xmlhttp;
	}

	function handleStateChange()
	{
		if (_httpobj.readyState != 4)
			return;

		onload_call(_httpobj, _httpurl);
	}
	
	try {
		_httpurl = url;
		_httpobj = createXMLHttpRequest();

		if (onload_call != null)
			_httpobj.onreadystatechange = handleStateChange;
		_httpobj.open(method, url, false);
		if (onsend_call != null)
			onsend_call(_httpobj, _httpurl);
		_httpobj.send(data);
	} catch (e) {	return false;	}

	return true;
}

function rvsweb_login(_u, _p, _r)
{
	var _as = location.pathname.split("/");
	if (_as[1] == "_")
		re_url = "/" + _as[1] + "/rweb/?login";
	else
		re_url = "/" + _as[1] + "/_/rweb/?login";

	var _data = "realm="+_r+"&user="+_u+"&pass="+_p;
	ajax('POST', re_url, _data, null, null);
}

function rvsweb_launch(_appid, _url)
{
	var chips = _url.match(/^(\/|https?:\/\/)/i);
	var re_url = '';
	if (chips == null)
		re_url = "/_P_HTTP/" + _url;
	else if (chips[0] == "https://")
		re_url += "/_P_HTTPS/" + _url.substring(chips[0].length);
	else
		re_url = "/_P_HTTP/" + _url.substring(chips[0].length);

	var _as = location.pathname.split("/");
	if (_as[1] == "_")
		re_url = "/" + _as[1] + "/rweb/" + _appid + re_url;
	else
		re_url = "/" + _as[1] + "/_/rweb/" + _appid + re_url;
	window.open(re_url);
}
