var GJSSYS_BROWSER_UNKNOWN = 0;
var GJSSYS_BROWSER_N451    = 1;
var GJSSYS_BROWSER_MS55    = 2;
var GJSSYS_BROWSER_MS50    = 3;
var GJSSYS_BROWSER_MS401   = 4;
var GJSSYS_BROWSER_N6      = 5;
var GJSSYS_BROWSER_MS6     = 6;
var GJSSYS_BROWSER_N70     = 7;
var GJSSYS_BROWSER_N71     = 8;
var GJSSYS_BROWSER_SAFARI  = 9;
var GJSSYS_BROWSER_FIREFOX = 10;

var PWdsapi_bIsIE;
var PWdsapi_bBrowserClassname;
var PWdsapi_eBrowser;
var PWdsapi_bActiveXEnabled = true;

var hexchars = "0123456789ABCDEF";
var okURIchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";
var PWdsapi_strPartionChars = ";/,.|+_)(*&^%$#@!~`\\=-[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

var M_clWdsApiFrame;

function wdsRequest() {

	this.m_oVars = new Object();
	
	this.m_strURL = window.top.G_strRootPath + "/" + "wdsAPI.aspx";
	
	this.Lang = "";
	
	this.Add = function(i_strName, i_strValue) {
		this.m_oVars[i_strName] = i_strValue;
	}
	
	this.Handler = function(i_oResponse, i_oUserData) {}
	
	this.ErrorHandler = function(i_oResponse, i_oUserData) { alert(i_oResponse.wdsError.message); }
	
	this.UserData = {};
	
	this.SetTableState = function(i_clForm) {
		this.Add("sWD_ReportId", i_clForm.sWD_ReportId.value);
		var nDims = i_clForm.sWD_MaxDim.value;
		this.Add("sWD_Rows", i_clForm.sWD_Rows.value);
		this.Add("sWD_Cols", i_clForm.sWD_Cols.value);
		this.Add("sWD_Others", i_clForm.sWD_Others.value);
		this.Add("sWD_DimActiveItemPos", i_clForm.sWD_DimActiveItemPos.value);
		for (var nDim = 0; nDim < nDims; nDim++) {
			var strDim = nDim.toString();
			this.Add("sWD_Chk" + strDim, i_clForm["sWD_Chk" + strDim].value);
			this.Add("sWD_Exp" + strDim, i_clForm["sWD_Exp" + strDim].value);
		}
	}
	
	this.GetRequest = function() {
		var strRequest = "WA=1";
		for (var strName in this.m_oVars) {
			strRequest += "&";
			strRequest += strName + "=" + p_UriEncode(this.m_oVars[strName]);
		}
		return strRequest;
	}
	
	this.GetRequestNoActiveX = function() {
		var strRequest = "";
		for (var strName in this.m_oVars) {
			strRequest += '<input type="hidden" name="' + strName + '" value="' + this.m_oVars[strName] + '">';
		}
		return strRequest;
	}
	
	this.p_PartitionedArray = function (i_astrStringArray) {
		for (var c = 0; c < PWdsapi_strPartionChars.length; c++) {
			var cChar = PWdsapi_strPartionChars.charAt(c);
			var bFound = false;
			for (var i = 0; i < i_astrStringArray.length; i++) {
				if (-1 != i_astrStringArray[i].indexOf(cChar)) {
					bFound = true;
				}
			}
			if (!bFound) {
				break;
			}
		}
		if (!bFound) {
			return cChar + i_astrStringArray.join(cChar);
		}
		else {
			alert("Internal error");
		}
		
	}
	
	this.p_ProcessResponse = function (i_strResponse, i_oRequest) {
		var strResponse = "(" + i_strResponse + ")";
		var oResponse = eval(strResponse);
		if (oResponse.wdsError) {
			if (typeof(i_oRequest.request.ErrorHandler) == "function") {
				i_oRequest.request.ErrorHandler(oResponse, i_oRequest.request.UserData);
			}
			else {
				alert(oResponse.wdsError.message);
			}
		}
		else {
			wdsSetState(i_oRequest.form, oResponse.state);
			if (typeof(i_oRequest.request.Handler) == "function") {
				i_oRequest.request.Handler(oResponse, i_oRequest.request.UserData);
			}
		}
	}
	
	this.ExecChangePassword = function(i_clForm, i_strUserName, i_strOldPassword, i_strNewPassword) {
		this.Add("WA_Command", "ChangePassword");
		this.Add("WA_UserName", i_strUserName);
		this.Add("WA_Password", i_strOldPassword);
		this.Add("WA_NewPassword", i_strNewPassword);
		this.p_LoadData({form:i_clForm, request:this});
	}
	
	this.ExecCreateFolder = function(i_clForm, i_strOwner, i_nParentFolderId, i_astrFolderName) {
		this.Add("WA_Command", "CreateFolder");
		this.Add("WA_UserName", i_clForm.LG_Login.value);
		this.Add("WA_Password", i_clForm.LG_pwd.value);
		this.Add("WA_Owner", i_strOwner);
		this.Add("WA_ParentFolderId", i_nParentFolderId.toString());
		this.Add("WA_FolderNames", this.p_PartitionedArray(i_astrFolderName));
		this.p_LoadData({request:this});
	}
	
	this.ExecGetData = function(i_nFirstRow, i_nFirstCol, i_nMaxRows, i_nMaxCols, i_clForm) {
		this.SetTableState(i_clForm);
		this.Add("WA_Command", "GetData");
		this.Add("WA_FirstRow", i_nFirstRow);
		this.Add("WA_MaxRows", i_nMaxRows);
		this.Add("WA_FirstCol", i_nFirstCol);
		this.Add("WA_MaxCols", i_nMaxCols);
		this.p_LoadData({form:i_clForm, request:this});
	}
	
	this.ExecGetFolderInfo = function(i_strUserName, i_strPassword, i_strOwner, i_nFolderId, i_nSortType) {
		this.Add("WA_Command", "GetFolderInfo");
		this.Add("WA_UserName", i_strUserName);
		this.Add("WA_Password", i_strPassword);
		this.Add("WA_Owner", i_strOwner);
		this.Add("WA_FolderId", i_nFolderId.toString());
		this.Add("WA_SortType", i_nSortType.toString());
		this.p_LoadData({request:this});
	}
	
	this.ExecGetFolderAccess = function(i_strUserName, i_strPassword, i_bWritable) {
		this.Add("WA_Command", "GetFolderAccess");
		this.Add("WA_UserName", i_strUserName);
		this.Add("WA_Password", i_strPassword);
		this.Add("WA_Writable", i_bWritable.toString());
		this.p_LoadData({request:this});
	}
	
	this.ExecGetFolderReportInfo = function(i_strUserName, i_strPassword, i_strReportName, i_nReportType, i_nFolderId) {
		this.Add("WA_Command", "GetFolderReportInfo");
		this.Add("WA_UserName", i_strUserName);
		this.Add("WA_Password", i_strPassword);
		this.Add("WA_ReportName", i_strReportName);
		this.Add("WA_ReportType", i_nReportType);
		this.Add("WA_FolderId", i_nFolderId);
		this.Add("sCS_ChosenLang", this.Lang);
		this.p_LoadData({request:this});
	}
	
	this.ExecGetReportInfo = function(i_strUserName, i_strPassword, i_nReportId) {
		this.Add("WA_Command", "GetReportInfo");
		this.Add("WA_UserName", i_strUserName);
		this.Add("WA_Password", i_strPassword);
		this.Add("WA_ReportId", i_nReportId);
		this.Add("sCS_ChosenLang", this.Lang);
		this.p_LoadData({request:this});
	}
	
	this.ExecLogin = function(i_strUserName, i_strPassword) {
		this.Add("WA_Command", "Login");
		this.Add("WA_UserName", i_strUserName);
		this.Add("WA_Password", i_strPassword);
		this.p_LoadData({request:this});
	}
	
	this.ExecOpenReport = function(i_nReportId, i_clForm) {
		this.Add("WA_Command", "OpenReport");
		this.Add("WA_ReportId", i_nReportId);
		this.p_LoadData({form:i_clForm, request:this});
	}
	
	this.ExecRecoverPassword = function(i_strUserName) {
		this.Add("WA_Command", "RecoverPassword");
		this.Add("WA_UserName", i_strUserName);
		this.p_LoadData({request:this});
	}
	
	this.ExecRegister = function(i_strUserName, i_strPassword, i_strFirst, i_strLast, i_strOrg, i_strEmail, i_strLang) {
		this.Add("WA_Command", "Register");
		this.Add("WA_UserName", i_strUserName);
		this.Add("WA_Password", i_strPassword);
		this.Add("WA_FirstName", i_strFirst);
		this.Add("WA_LastName", i_strLast);
		this.Add("WA_Organization", i_strOrg);
		this.Add("WA_Email", i_strEmail);
		this.Add("sCS_ChosenLang", i_strLang);
		this.p_LoadData({request:this});
	}
	
	this.ExecRenameReport = function(i_strUserName, i_strPassword, i_anReportId, i_astrReportName, i_astrLang, i_bIncludePA) {
		this.Add("WA_Command", "RenameReport");
		this.Add("WA_UserName", i_strUserName);
		this.Add("WA_Password", i_strPassword);
		this.Add("WA_ReportId", i_anReportId.join(","));
		this.Add("WA_ReportName", this.p_PartitionedArray(i_astrReportName));
		this.Add("WA_Lang", this.p_PartitionedArray(i_astrLang));
		this.Add("WA_IncludePA", i_bIncludePA ? "True" : "False");
		this.Add("sCS_ChosenLang", this.Lang);
		this.p_LoadData({request:this});
	}
	
	this.p_LoadData = function(i_clUserData) {
		if (PWdsapi_bActiveXEnabled) {
			wdsLoadData(this.m_strURL, this.GetRequest(), this.p_ProcessResponse, i_clUserData);
		}
		else {
			wdsLoadPage(this.m_strURL, this.GetRequestNoActiveX(), this.p_ProcessResponse, i_clUserData);
		}
	}
};

function wdsSetState(i_clForm, i_oState) {
	for (var strName in i_oState) {
		wdsCreateFormField(i_clForm, strName, i_oState[strName]);
	}
}
	
function wdsCreateFormField(i_clForm, i_strFieldName, i_strFieldValue) {
	var nIndex = -1;
	for (var i = i_clForm.elements.length - 1; i >= 0; i--) {
		if (i_clForm.elements[i].name == i_strFieldName) {
			nIndex = i;
			break;
		}
	}
	if (nIndex == -1) {
		var clInputTag = document.createElement("input");
		clInputTag.setAttribute("type", "hidden", 0);
		clInputTag.setAttribute("name", i_strFieldName, 0);
		clInputTag.setAttribute("id", i_strFieldName, 0);
		clInputTag.setAttribute("value", i_strFieldValue, 0);
		try {
			i_clForm.appendChild(clInputTag);
		}
		catch (e) {
			var strName = i_clForm.id;
			window.top[strName].appendChild(clInputTag);
		}
	}
	else {
		i_clForm.elements[nIndex].value = i_strFieldValue;
	}
}

function wdsRemoveFormField(i_clForm, i_strName) {
	var aclFields;
	var clField;
	var nFieldCount;
	var nIndex;
	
	aclFields = i_clForm[i_strName];
	if (aclFields != undefined) {
		if (aclFields.length == undefined) {
			aclFields.parentNode.removeChild(aclFields);
		}
		else {
			nFieldCount = aclFields.length;
			for (nIndex = nFieldCount - 1; nIndex >= 0; nIndex--) {
				clField = aclFields[nIndex];
				clField.parentNode.removeChild(clField);
			}
		}
	}
}

function p_InitActiveX() {
	PWdsapi_bActiveXEnabled = true;
	if (PWdsapi_bIsIE) {
		PWdsapi_bActiveXEnabled = false;
		try {
			clXmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
			PWdsapi_bActiveXEnabled = true;
		}
		catch(ex) {
		}
	}
}

function p_InitBrowser() {
	var dAppVersion;
	var strAppName;

	PWdsapi_bIsIE = false;
	PWdsapi_bBrowserClassname = true;
	strAppName = navigator.appName;
	if (strAppName == "Netscape") {
		var strUserAgent = window.navigator.userAgent.toLowerCase();
		if (strUserAgent.indexOf("firefox") > 0) {
			PWdsapi_bBrowserClassname = false;
			PWdsapi_eBrowser = GJSSYS_BROWSER_FIREFOX;
		}
		else if (strUserAgent.indexOf("netscape") > 0) {
			PWdsapi_bBrowserClassname = false;
			dAppVersion = parseFloat(navigator.appVersion);
			if (dAppVersion >= 5.0) {
				PWdsapi_eBrowser  = GJSSYS_BROWSER_N6;
				dAppVersion = parseFloat(navigator.userAgent.split("Netscape/")[1]);
				if( dAppVersion == 7.0 )
					PWdsapi_eBrowser = GJSSYS_BROWSER_N70;
				else if( dAppVersion >= 7.1 )
					PWdsapi_eBrowser = GJSSYS_BROWSER_N71;
			}
			else if (dAppVersion >= 4.51) {
				PWdsapi_eBrowser  = GJSSYS_BROWSER_N451;
			}
		}
		else if (strUserAgent.indexOf("safari") > 0) {
			PWdsapi_eBrowser = GJSSYS_BROWSER_UNKNOWN;
		}
		else {
			PWdsapi_eBrowser = GJSSYS_BROWSER_UNKNOWN;
		}
	}
	else if (strAppName == "Microsoft Internet Explorer") {
		PWdsapi_bIsIE = true;
		dAppVersion = parseFloat(navigator.appVersion.split("MSIE")[1]);

		if (dAppVersion >= 6.0) {
			PWdsapi_eBrowser = GJSSYS_BROWSER_MS6;
		}
		else if (dAppVersion >= 5.5) {
				PWdsapi_eBrowser = GJSSYS_BROWSER_MS55;
		}
		else if (dAppVersion >= 5.0) {
			PWdsapi_eBrowser = GJSSYS_BROWSER_MS50;
		}
		else if (dAppVersion >= 4.01) {
			PWdsapi_eBrowser = GJSSYS_BROWSER_MS401;
		}
	}
	else {
		PWdsapi_eBrowser = GJSSYS_BROWSER_UNKNOWN;
	}
}


function wdsInit() {
	p_InitBrowser();
	p_InitActiveX();
}

function wdsLoadData(i_strURL, i_strRequest, i_fnHandler, i_clUserData) {
	var clXmlHttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP.3.0");
	if (typeof(clXmlHttp) != "undefined") {
		clXmlHttp.open("POST", i_strURL + "?", true);
		clXmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		clXmlHttp.onreadystatechange = function() {
			if (clXmlHttp.readyState == 4) {
				if (clXmlHttp.status == 200) {
					if (clXmlHttp.responseText) {
						i_fnHandler(clXmlHttp.responseText, i_clUserData);
					}
					else {
						alert("No XmlHttp responseText");
					}
				}
				else {
					alert("XmlHttp status is " + clXmlHttp.status + " for URL " + i_strURL);
				}
			}
		}
		clXmlHttp.send(i_strRequest);
	}
	else {
		alert("Unable to establish XmlHttp request object.");
	}
}

function p_UTF8(wide) {
	var c, s;
	var strResult = "";
	var i = 0;
	while (i < wide.length) {
		c = wide.charCodeAt(i++);
		if (c >= 0xDC00 && c < 0xE000) {
			continue;
		}
		if (c >= 0xD800 && c < 0xDC00) {
			if (i >= wide.length) {
				continue;
			}
			s = wide.charCodeAt(i++);
			if (s < 0xDC00 || c >= 0xDE00) {
				continue;
			}
			c = ((c - 0xD800) << 10) + (s - 0xDC00) + 0x10000;
		}
		if (c < 0x80) {
			strResult += String.fromCharCode(c);
		}
		else if (c<0x800) {
			strResult += String.fromCharCode(0xC0 + (c >> 6), 0x80 + (c & 0x3F));
		}
		else if (c < 0x10000) {
			strResult += String.fromCharCode(0xE0 + (c >> 12), 0x80 + (c >> 6 & 0x3F), 0x80 + (c & 0x3F));
		}
		else {
			strResult += String.fromCharCode(0xF0 + (c >> 18), 0x80 + (c >> 12 & 0x3F), 0x80 + (c >> 6 & 0x3F), 0x80 + (c & 0x3F));
		}
	}
	return strResult;
}

function p_ToHex(n) {
	return hexchars.charAt(n>>4)+hexchars.charAt(n & 0xF);
}

function p_EncodeUriComponentOld(i_strString) {
	var s = p_UTF8(i_strString);
	var c;
	var strResult = "";
	for (var i = 0; i < s.length; i++) {
		if (okURIchars.indexOf(s.charAt(i)) == -1) {
			strResult += "%" + p_ToHex(s.charCodeAt(i));
		}
		else {
			strResult += s.charAt(i);
		}
	}
	return strResult;
}

function p_UriEncode(i_strString) {
	if (typeof(encodeURIComponent) == "function") {
		return encodeURIComponent(i_strString);
	}
	else {
		return p_EncodeUriComponentOld(i_strString);
	}
}

function wdsLoadPage(i_strURL, i_strRequest, i_fnHandler, i_clUserData) {
	var iframeDoc;

	try {
		if (M_clWdsApiFrame == undefined && document.createElement) {
			// Create the IFrame and assign a reference to the
			// object to our global variable M_clWdsApiFrame.
			// this will only happen the first time loadPage() is called
			var tempIFrame = document.createElement('iframe');
			tempIFrame.setAttribute('id', 'MyIFrame');
			tempIFrame.style.border = '0px';
			tempIFrame.style.width = '0px';
			tempIFrame.style.height = '0px';
			M_clWdsApiFrame = document.body.appendChild(tempIFrame);
			if (document.frames) {
				// Access the document object of the IFrame
				// through the document.frames array
				M_clWdsApiFrame = document.frames['MyIFrame'];
			}
		}
		if (M_clWdsApiFrame.document) {
			iframeDoc = M_clWdsApiFrame.document;
		}
	}
	catch(ex) {
		alert("Failure to access IFrame");
	}
	document.wdsApiCallbackHandler = function (i_strResponse) {
		i_fnHandler(i_strResponse, i_clUserData);
	}

	// call a server routine from client code
	iframeDoc.POST = wdsLoadDataToIFrame;
	// i_strUrl: href to asp file 
	iframeDoc.POST(i_strURL, i_strRequest);
}

function wdsLoadDataToIFrame(i_strUrl, i_strRequest) {
	this.open();
	this.write('<html><body>');
	this.write('<form name="iframeForm" method="post" target="" action="');
	this.write(i_strUrl);
	this.write('"><input type="hidden" name="WA_IFrame" value="True">');
	this.write(i_strRequest);
	this.write('</form></body></html>');
	this.location.replace(i_strUrl);
	this.close();
	this.forms['iframeForm'].submit();
}

function wdsApiIframeHandler(i_clDoc) {
	document.wdsApiCallbackHandler(i_clDoc.body.innerText);
}

wdsInit();

