// util.js

window.initFocusId = "undefined";
window.scrollToId  = "undefined";

function pageInit() {
	window.setTimeout(setInitFocus, 10);
	window.setTimeout(scrollTo, 20);
	return;
}

function setInitFocus() {
	if(initFocusId != "undefined") {
		var obj = document.getElementById(initFocusId);
		if(obj && obj.focus) {
			obj.focus();
		}
	}
}

function scrollTo() {
	if(scrollToId != "undefined") {
		window.location.href = "#" + scrollToId;
	}
}

function setTabbedPanelState() {
//	alert('in setTabbedPanelState(): tabPanelState=' + tabPanelState);
	if(tabPanelState != 'undefined') {
		var panel = ODCRegistry.getClientControl('tabbedPanel1');
		panel.restoreUIState(tabPanelState);
	}
	return true;
}


function logout() {
	window.location.href = '/hjip/logout.jsp';
}


function submitForm(thisObj, thisEvent) {
	return thisObj.form.submit();
}

/*
 * Selects a node content text
 */
function selectNodeText (node) {
	var selection, range, doc, win;
	if ((doc = node.ownerDocument) && (win = doc.defaultView) && typeof
		win.getSelection != 'undefined' 
		&& typeof doc.createRange != 'undefined'
		&& (selection = window.getSelection()) && typeof selection.removeAllRanges != 'undefined') {
			range = doc.createRange();
			range.selectNode(node);
			selection.removeAllRanges();
			selection.addRange(range);
	} else if (document.body 
		&& typeof document.body.createTextRange != 'undefined' 
		&& (range = document.body.createTextRange())) {
			range.moveToElementText(node);
			range.select();
	}
}

function selectNode (node) {
	selectNodeText (node);
}

function openMessage() {
	window.open();
}

function confirmSubmit(thisObj, thisEvent) {
	return confirm('Click OK if you pasted new complete message body in the field. This field contains a partial message text when displayed from the Resubmit Queue. If you are unsure then click Cancel.');
}

//***************************************************************************************
// Dependant windows
//***************************************************************************************
var dependentWindows = new Array();

function addDependent(win) {
    dependentWindows[dependentWindows.length] = win;
}
function removeAll() {
    for(var i=0; i<dependentWindows.length; i++) {
        if(dependentWindows[i])
            dependentWindows[i].close();
    }
}
//***************************************************************************************
// Row highlighting functions 
//***************************************************************************************
function setupRowHighlight(tblId, rowCount) {
    var i,j,t,b,r;
    t = document.getElementById(tblId);
    if (t!=null){
        b = t.tBodies[0];
        if (b.rows!=undefined) {
            for (j=0; j<b.rows.length && (!rowCount || rowCount && j<rowCount); j++) {
                r = b.rows[j];
                if (document.body.addEventListener) {
                    r.addEventListener("mouseover", rowColor, true);
                    r.addEventListener("mouseout", rowColor, true);
                } else {
                    r.setAttribute("onmouseover", rowColor);
                    r.setAttribute("onmouseout", rowColor);
                }
            }
        }
    }
    return true;
}

function rowColor (evt) {
    evt = (evt)?evt:event;
    var tgt = (evt==null)?null:((evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null));
    while (tgt!=null && tgt.tagName.toUpperCase()!="TR") tgt = tgt.parentNode;
    if (tgt!=null && tgt.cells!=undefined) {
        var c="rowHighlight", k=c.length, cl,wasCl,i,j,td;
        for (i=0; i<tgt.cells.length; i++) {
            td = tgt.cells[i];
            cl = wasCl = td.className;
            j = cl.indexOf(c);
            if (evt.type=="mouseover") {
                cl += (j<0) ? (" "+c) : "";
            } else {
                if (j>=0) {
                    if (cl.charAt(j-1)==" ") { j--; k++; }
                    cl = cl.substr(0,j) + cl.substr(j+k);
                }
            }
            if (cl!=wasCl) td.className = cl;
        }
    }
    return true;
}				
// Row highlighting functions end

//***************************************************************************************
// Show wait and screen blocking 
//***************************************************************************************
function showWait(evt) {
//	alert("int showWait("+evt+")");
	var	standardbody  = (document.compatMode=="CSS1Compat") ? document.documentElement : document.body; 
	var progressPanel = document.getElementById("progressPanel"); 
	var pageVeil      = document.getElementById("pageVeil"); 
	var ie  = document.all && !window.opera;
	var dom = document.getElementById;
	var scroll_top = (ie)? standardbody.scrollTop : window.pageYOffset;
	var scroll_left= (ie)? standardbody.scrollLeft : window.pageXOffset;
	var docwidth   = (ie)? standardbody.clientWidth : window.innerWidth; // - scrollbarwidth;
	var docheight  = (ie)? standardbody.clientHeight: window.innerHeight;
	var docheightcomplete = (standardbody.offsetHeight > standardbody.scrollHeight) ? standardbody.offsetHeight : standardbody.scrollHeight;
	//set up, position and show veil over page
	pageVeil.style.width = docwidth + "px"; 			
	pageVeil.style.height= docheightcomplete + "px"; 	
	pageVeil.style.left  = 0; 							
	pageVeil.style.top   = 0; 							
	pageVeil.style.visibility = "visible"; 				
	//Position box
	var objwidth   = progressPanel.offsetWidth;
	var objheight  = progressPanel.offsetHeight;
	var topposition = (docheight > objheight) ? scroll_top + docheight/3 - objheight/2 : scroll_top + 5; 
	topposition = topposition < 250 ? 250 : topposition;
	progressPanel.style.left = (docwidth/2 - objwidth/2) + "px"; 
	progressPanel.style.top = Math.floor(parseInt(topposition)) + "px";
	//Show box
	progressPanel.style.visibility = "visible";
	progressPanel.style.display    = "block";				
//	alert("objwidth="+objwidth+" objheight="+objheight+" docwidth="+docwidth+" docheight="+docheight+" progressPanel.style.left="+progressPanel.style.left+" progressPanel.style.top="+progressPanel.style.top);
	
}

function hideWait() {
	var progressPanel = document.getElementById("progressPanel"); 
	var pageVeil      = document.getElementById("pageVeil"); 
	if(progressPanel) {
		progressPanel.style.visibility = "hidden";
		progressPanel.style.display    = "none";				
	}
	if(pageVeil) {
		pageVeil.style.visibility = "hidden"; 				
	}
}

//***************************************************************************************
// Request async report 
//***************************************************************************************
var checkStatusLimit = 120; // cycles 1000 ms each = 2 minutes
var checkStatusNo    = 0;
var delayMs          = 1000; // ms
//var contextRoot = "/hjip";  // must be defined earlier in the layout
var reportUrl = contextRoot + "/report";
var reportRequested = false;

/* 
 * Show "please wait..." and window veil, then send initial report request 
 * using getStatus() as the response handler 
 */
function sendReportRequest(url, parameters) {
	if(!reportRequested) {
		reportRequested = true;
		loader = new net.ContentLoader(url, getStatus, errorHandler);
		showWait();
		loader.sendPost(url, parameters);
	}
}
/* 
 * Parse report status response XML message. 
 * If status text is REQUESTED, then continue with check status after a delay. 
 * If status text is DONE, then send report data request with window redirect. 
 */
function getStatus() {
	var status   = loader.req.responseXML.getElementsByTagName('ReportStatus')[0];
	var authorId  = status.childNodes[0].childNodes[0].nodeValue;
	var reportId  = status.childNodes[1].childNodes[0].nodeValue;
	var requestId = status.childNodes[2].childNodes[0].nodeValue;
	var statusTxt = status.childNodes[3].childNodes[0].nodeValue;
	//alert('getStatus(): authorId='+authorId+' reportId='+reportId+' requestId='+requestId+' statusTxt='+statusTxt);
	if(statusTxt) {
		if(statusTxt == 'REQUESTED') {
			//alert('REQUESTED')
			// check timeout
			if(checkStatusNo < checkStatusLimit) {
				//alert('checking status')
				var func = "checkStatus('"+authorId+"', '"+reportId+"', '"+requestId+"')";
				window.setTimeout(func, delayMs);
			} else {
				window.location.href = contextRoot + '/faces/errorpage.jsp?timeout='+(delayMs * checkStatusNo);
			}
	 	} else if(statusTxt == 'FAILED') {
	 		//alert('FAILED')
	 		window.location.href = contextRoot + '/faces/errorpage.jsp?status=FAILED';
	 	} else if(statusTxt == 'DONE') {
			//alert('DONE')
	 		getData(authorId, reportId, requestId);
	 	} else {
	 		window.alert('Wrong response received: ' + statusTxt);
	 	}
	}
}
/*
 * Redirect to error page on AJAX error
 */
function errorHandler() {
	window.location.href = contextRoot + '/faces/errorpage.jsp?status=FAILED';
}

/* 
 * Send check report status request using getStatus as the response handler 
 */
function checkStatus(authorId, reportId, requestId) {
//	alert('checkStatus()')
	checkStatusNo = checkStatusNo + 1;
	var url = reportUrl + '?status=1&' + encodeRequest(authorId, reportId, requestId);
	loader = new net.ContentLoader(url, getStatus, errorHandler); // have to get new for IE
	loader.url = url;
	loader.onload = getStatus;
	loader.sendGet(url);
}
/* 
 * Hide "please wait..." and window veil, then redirect window with report data request 
 */
function getData(authorId, reportId, requestId) {
//	alert('getData(): authorId='+authorId+' reportId='+reportId+' requestId='+requestId);
	var url = reportUrl + '?data=1&' + encodeRequest(authorId, reportId, requestId);
	hideWait();
	window.location.href = url;
}

function encodeRequest(authorId, reportId, requestId) {
	var query = 'authorId=' + escape(authorId)
			+ '&reportId=' + escape(reportId)
			+ '&requestId=' + escape(requestId);
	return query;
}

