/////////////////////////////////////////////////////////////////
function doPageStyling() {
	//var trace = new Date();
	try {
		var inputs;
		inputs = document.forms['ICONFORM'].elements;
		for (var i=0;i<inputs.length;i++) {
			if (!inputs[i].className) {
				switch(inputs[i].type) {
					case 'text':
					case 'textarea':
					case 'password':
						inputs[i].className = 'txt';
						break;
					case 'select-one':
						//inputs[i].className = 'wcbo';
						break;
					case 'submit':
					case 'button':
						inputs[i].className = 'wbtn';
						break;
				}
			}
		}
	}
	catch (e) {
	}
	//var traceend = new Date();
	//alert(traceend.getTime()-trace.getTime());
}

function spell(elementname)
{
	window.open("/ActiveSpell/spellchecker/window.asp?jsvar=document.ICONFORM."+elementname+".value",null, "height=230,width=450,status=no,toolbar=no,menubar=no,location=no");
}

function closewindowfocusopener() {
	if (window.opener) window.opener.focus();
	window.close();
}

//------------------------------------------------------------------------------
function getlayer(layerName) {if (document.layers) {return eval('document.' + layerName);}else {if (document.all) {return eval('document.all.' + layerName + '.style');}else {return eval('document.getElementById("' + layerName + '").style');}}}
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
function StoreDataToDiv(divname, data) {
	if (document.all[divname]) {
		document.all[divname].innerHTML='';
		document.all[divname].insertAdjacentHTML('afterBegin',data);
	}
}

/////////////////////////////////////////////////////////////////


//------------------------------------------------------------------------------

function DecodeRemoteData(data) {
	//return data;
	var decoded = data;
	//decoded = decodeURI(unescape(decoded));
	//decoded=replaceString(decoded, '[PERCENT]', '%');
	//return decoded; //
	decoded = replaceString(decoded, '[PERCENT]', '%');
	decoded = replaceString(decoded, '[EQUALSIGN]', '=');
	decoded = replaceString(decoded, '[AMP]', '&');
	decoded = replaceString(decoded, '[AT]', '@');
	decoded = replaceString(decoded, '[PLUS]', '+');
	decoded = replaceString(decoded, '[MINUS]', '-');
	decoded = replaceString(decoded, '[LT]', '<');
	decoded = replaceString(decoded, '[GT]', '>');
	decoded = replaceString(decoded, '[CRLF]', '\n');
	decoded = replaceString(decoded, '[QUOTE]', '"');
	return decoded;
}

//------------------------------------------------------------------------------
function replaceString(s, whatToFind, replaceWith) {
	if (whatToFind == replaceWith) return s;
	while (s.indexOf(whatToFind) != (-1)) {
		s = s.replace(whatToFind, replaceWith);
	}
	return s;
}

//------------------------------------------------------------------------------
function SetWaitCursor(show)
{
	// new logic - set wait cursor only for originating element
	if (self.eventSourceElement) {
		SetWaitCursorForElement(self.eventSourceElement,show,false);
	}
}

//
//  jsrsClient.js - javascript remote scripting client include
//  
//  Author:  Brent Ashley [jsrs@megahuge.com]
//
//  make asynchronous remote calls to server without client page refresh
//
//  see license.txt for copyright and license information

/*
see history.txt for full history
2.0  26 Jul 2001 - added POST capability for IE/MOZ
*/

// callback pool needs global scope
var jsrsContextPoolSize = 0;
var jsrsContextMaxPool = 10;
var jsrsContextPool = new Array();
var jsrsBrowser = jsrsBrowserSniff();
var jsrsPOST = true;

// constructor for context object
function jsrsContextObj( contextID ){
  
  // properties
  this.id = contextID;
  this.busy = true;
  this.callback = null;
  this.container = contextCreateContainer( contextID );
  
  // methods
  this.GET = contextGET;
  this.POST = contextPOST;
  this.getPayload = contextGetPayload;
  this.setVisibility = contextSetVisibility;
}

//  method functions are not privately scoped 
//  because Netscape's debugger chokes on private functions
function contextCreateContainer( containerName ){
  // creates hidden container to receive server data 
  var container;
  switch( jsrsBrowser ) {
    case 'NS':
      container = new Layer(100);
      container.name = containerName;
      container.visibility = 'hidden';
      container.clip.width = 100;
      container.clip.height = 100;
      break;
    
    case 'IE':
      document.body.insertAdjacentHTML( "afterBegin", '<span id="SPAN' + containerName + '"></span>' );
      var span = document.all( "SPAN" + containerName );
      var html = '<iframe name="' + containerName + '" src="blank.htm"></iframe>';
      span.innerHTML = html;
      span.style.display = 'none';
      container = window.frames[ containerName ];
      break;
      
    case 'MOZ':  
      var span = document.createElement('SPAN');
      span.id = "SPAN" + containerName;
      document.body.appendChild( span );
      var iframe = document.createElement('IFRAME');
      iframe.name = containerName;
      span.appendChild( iframe );
      container = iframe;
      break;
  }
  return container;
}

function contextPOST( rsPage, func, parms ){

  var d = new Date();
  var unique = d.getTime() + '' + Math.floor(1000 * Math.random());
  var doc = (jsrsBrowser == "IE" ) ? this.container.document : this.container.contentDocument;
  doc.open();
  doc.write('<html><body>');
  doc.write('<form name="jsrsForm" method="post" target="" ');
  doc.write(' action="' + rsPage + '&U=' + unique + '">');
  doc.write('<input type="hidden" name="C" value="' + this.id + '">');
  doc.write('<input type="hidden" name="F" value="' + func + '">');
  
  if (parms != null){
  
	  if (typeof(parms) == "string"){
			var autoParams = parms.split('&');	// pxw1 - split to array anyways
			if (autoParams.length > 0) {
				parms = autoParams;
			}
		}
		
		var realParms;
				
    // assume parms is array of strings
    for( var i=0; i < parms.length; i++ ){
			realParms = parms[i].split('=');
			if (realParms.length == 2) {
				doc.write( '<input type="hidden" name="' + DecodeRemoteData(realParms[0]) + '" '
					+ 'value="' + jsrsEscapeQQ(DecodeRemoteData(realParms[1])) + '">');
			}
    }
    
  }
  doc.write('</form></body></html>');
  doc.close();
  //alert(doc.body.innerHTML);
  doc.forms['jsrsForm'].submit();
}

function contextGET( rsPage, func, parms ){

  // build URL to call
  var URL = rsPage;

  // always send context
  URL += "?C=" + this.id;

  // func and parms are optional
  if (func != null){
    URL += "&F=" + escape(func);

    if (parms != null){
      if (typeof(parms) == "string"){
        // single parameter
        URL += "&P0=[" + escape(parms+'') + "]";
      } else {
        // assume parms is array of strings
        for( var i=0; i < parms.length; i++ ){
          URL += "&P" + i + "=[" + escape(parms[i]+'') + "]";
        }
      } // parm type
    } // parms
  } // func

  // unique string to defeat cache
  var d = new Date();
  URL += "&U=" + d.getTime();
 
  // make the call
  switch( jsrsBrowser ) {
    case 'NS':
      this.container.src = URL;
      break;
    case 'IE':
      this.container.document.location.replace(URL);
      break;
    case 'MOZ':
      this.container.src = '';
      this.container.src = URL; 
      break;
  }  
  
}

function contextGetPayload(){
  switch( jsrsBrowser ) {
    case 'NS':
      return this.container.document.forms['jsrs_Form'].elements['jsrs_Payload'].value;
    case 'IE':
      return this.container.document.forms['jsrs_Form']['jsrs_Payload'].value;
    case 'MOZ':
      return window.frames[this.container.name].document.forms['jsrs_Form']['jsrs_Payload'].value; 
  }  
}

function contextSetVisibility( vis ){
  switch( jsrsBrowser ) {
    case 'NS':
      this.container.visibility = (vis)? 'show' : 'hidden';
      break;
    case 'IE':
      document.all("SPAN" + this.id ).style.display = (vis)? '' : 'none';
      break;
    case 'MOZ':
      document.getElementById("SPAN" + this.id).style.visibility = (vis)? '' : 'hidden';
      this.container.width = (vis)? 250 : 0;
      this.container.height = (vis)? 100 : 0;
      break;
  }  
}

// end of context constructor

function jsrsGetContextID(){
  var contextObj;
  for (var i = 1; i <= jsrsContextPoolSize; i++){
    contextObj = jsrsContextPool[ 'jsrs' + i ];
    if ( !contextObj.busy ){
      contextObj.busy = true;      
      return contextObj.id;
    }
  }
  // if we got here, there are no existing free contexts
  if ( jsrsContextPoolSize <= jsrsContextMaxPool ){
    // create new context
    var contextID = "jsrs" + (jsrsContextPoolSize + 1);
    jsrsContextPool[ contextID ] = new jsrsContextObj( contextID );
    jsrsContextPoolSize++;
    return contextID;
  } else {
    alert( "jsrs Error:  context pool full" );
    return null;
  }
}
function jsrsExecute( rspage, parms, callback, visibility, func ) {
  // call a server routine from client code
  //
  // rspage      - href to asp file
  // callback    - function to call on return 
  //               or null if no return needed
  //               (passes returned string to callback)
  // func        - sub or function name  to call
  // parm        - string parameter to function
  //               or array of string parameters if more than one
  // visibility  - optional boolean to make container visible for debugging
  
  // get context
  var contextObj = jsrsContextPool[ jsrsGetContextID() ];
  contextObj.callback = callback;
  
  var vis = (visibility == null)? false : visibility;
  contextObj.setVisibility( vis );

  if ( jsrsPOST && ((jsrsBrowser == 'IE') || (jsrsBrowser == 'MOZ'))){
    contextObj.POST( rspage, func, parms );
  } else {
    contextObj.GET( rspage, func, parms );
  }  
  
  return contextObj.id;
}

function jsrsLoaded( contextID ){
	SetWaitCursor(false);
  // get context object and invoke callback
  var contextObj = jsrsContextPool[ contextID ];
  if( contextObj.callback != null){
		contextObj.callback( jsrsUnescape( contextObj.getPayload() ), contextID );
  }
  // clean up and return context to pool
  contextObj.callback = null;
  contextObj.busy = false;
}

function jsrsError( contextID, str ){
  alert( unescape(str) );
  jsrsContextPool[ contextID ].busy = false
}

function jsrsEscapeQQ( thing ){
	var s = thing;
	while (s.indexOf('"') != (-1)) {
		s = s.replace('"', '&quot;');
	}
	return s;
}

function jsrsUnescape( str ){
  // payload has slashes escaped with whacks
  return str.replace( /\\\//g, "/" );
}

function jsrsBrowserSniff(){
  if (document.layers) return "NS";
  if (document.all) return "IE";
  if (document.getElementById) return "MOZ";
  return "OTHER";
}

/////////////////////////////////////////////////
//
// user functions

function jsrsArrayFromString( s, delim ){
  // rebuild an array returned from server as string
  // optional delimiter defaults to ~
  var d = (delim == null)? '~' : delim;
  return s.split(d);
}

function jsrsDebugInfo(){
  // use for debugging by attaching to f1 (works with IE)
  // with onHelp = "return jsrsDebugInfo();" in the body tag
  var doc = window.open().document;
  doc.open;
  doc.write( 'Pool Size: ' + jsrsContextPoolSize + '<br><font face="arial" size="2"><b>' );
  for( var i in jsrsContextPool ){
    var contextObj = jsrsContextPool[i];
    doc.write( '<hr>' + contextObj.id + ' : ' + (contextObj.busy ? 'busy' : 'available') + '<br>');
    doc.write( contextObj.container.document.location.pathname + '<br>');
    doc.write( contextObj.container.document.location.search + '<br>');
    doc.write( '<table border="1"><tr><td>' + contextObj.container.document.body.innerHTML + '</td></tr></table>' );
  }
  doc.write('</table>');
  doc.close();
  return false;
}

//--- SUGGEST COMBO FUNCTIONS ---------------------------------------------------

var _inputField=null;
var _activeCombo=null;
var _comboFieldValue="";
var _searchInitiated=false;
var _RemoteExecutionHandler=null;
var _EnterHandler=null;
var _doSearchTimeout=null;
var _enterPressed=false;
var _resultCache=new Object();
var _resultCacheContext=null;

function installSuggest(ctrl,div,remoteExecutionHandler,enterHandler) {
	_RemoteExecutionHandler=remoteExecutionHandler;
	_EnterHandler=enterHandler;
	_inputField=ctrl;
	_inputField.autocomplete="off";
	if(_inputField.createTextRange) {
	  _inputField.onkeyup=new Function("return onKeyUp(event);");
	} else {
	  _inputField.onkeyup=onKeyUp;
	}
	_activeCombo=div;
	_resultCache=new Object();
	_resultCacheContext=null;
	initComboBox();
}

function onKeyUp(e){
  eventKeycode=e.keyCode;
  inputFieldValue=_inputField.value;
  if(inputFieldValue.length==0) hideCombo();
  else if(_comboFieldValue!=inputFieldValue && !_searchInitiated) {
  	_searchInitiated=true;
  	_doSearchTimeout=setTimeout("doSearch()",250);
  }
  if(eventKeycode==13) {
		_enterPressed=true;
		hideCombo();
		_EnterHandler();
  }
  else _enterPressed=false;
}

function cacheResult(key,data){
  _resultCache[key]=data
}

function doSearch() {
	if(_doSearchTimeout!=null) {
		clearTimeout(_doSearchTimeout);
		_doSearchTimeout=null;
	}
	if(_inputField.value.length>0) {
		_comboFieldValue=_inputField.value;
    var data=_resultCache[_comboFieldValue];
    if(data) {
		if(data!="--") fillCombo(data);
	}
   	else _RemoteExecutionHandler(_comboFieldValue); // the remote execution handler should call the function fillCombo(data) to show the combo with data
	}
	_searchInitiated=false;
}

function findPosX(obj) {
    var curleft = 0; 
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curleft += obj.offsetLeft - obj.scrollLeft; 
            obj = obj.offsetParent; 
        } 
    } else if (obj.x) {
        curleft += obj.x; 
    }
    return curleft; 
}

function findPosY(obj) {
    var curtop = 0; 
    if (obj.offsetParent) {
        while (obj.offsetParent) { 
            curtop += obj.offsetTop - obj.scrollTop; 
            obj = obj.offsetParent; 
        }
    } else if (obj.y) {
        curtop += obj.y;
    }
    return curtop;
}

function showCombo() {
	if(_enterPressed==true) return;
	if(_activeCombo==null) return;
	if(_inputField==null) return;
    var text = _activeCombo;
    var inputElem = _inputField;
    var inputWidth = inputElem.offsetWidth;
    var inputHeight = inputElem.offsetHeight;
    if (text.style.visibility == "visible") {
        return;
    }
    var x = findPosX(inputElem);
    var y = findPosY(inputElem) + inputHeight - 1;
    var textHeight = text.offsetHeight;
    var textWidth = text.offsetWidth;
    var scrollSize = 20;    
    var scrollTop = 0;
    var scrollLeft = 0;
    var clientHeight = 0;
    var clientWidth = 0;
    if (document.documentElement && (document.documentElement.scrollTop || document.documentElement.clientHeight)) {
    	// NS
        scrollTop = document.documentElement.scrollTop;
        scrollLeft = document.documentElement.scrollLeft;
        clientHeight = document.documentElement.clientHeight;
        clientWidth = document.documentElement.clientWidth;
    } else if (document.body) {
    	// IE
        scrollTop = document.body.scrollTop;
        scrollLeft = document.body.scrollLeft;
        clientHeight = document.body.clientHeight;
        clientWidth = document.body.clientWidth;
    }
/*    if ((y + textHeight) > (clientHeight + scrollTop)) {
        y = y - textHeight;
    }
    if (y < scrollTop) {
        y = (clientHeight + scrollTop) - (textHeight + scrollSize);
    }
    if (y < scrollTop) {
        y = scrollTop;
    }*/
    if ((x + textWidth) > (clientWidth + scrollLeft)) {
        x = x - textWidth;
    }  
    if (x < scrollLeft) {
        x = (clientWidth + scrollLeft) - (textWidth + scrollSize);
    }
    if (x < scrollLeft) {
        x = scrollLeft;
    }
    text.style.left = x + "px";
    text.style.top =  y + "px";
//	    text.style.width = inputWidth + "px";
    text.style.visibility = "visible";
}

function hideCombo() {
	_comboFieldValue=""
	if (_activeCombo != null) {
		_activeCombo.style.visibility = "hidden";
	}
}

function setComboValue(itemId, value) {
    var item = document.getElementById(itemId);   
    item.value = value;
    item.select();
    item.focus();
    hideCombo();
    _comboFieldValue=value;
}

function initComboBox() {
	if (document.addEventListener) {
		document.addEventListener("mouseup", hideCombo, false );
	}
	else if (document.attachEvent) {
		document.attachEvent("onmouseup", function () { hideCombo(); } );
	}
  Global_run_event_hook = false;
}

function fillCombo(data) {
	if(data.length>0) {
		cacheResult(_comboFieldValue,data);
		StoreDataToDiv(_activeCombo.id, data);
		showCombo();
	}
	else cacheResult(_comboFieldValue,"--");
}

function setAndEnableField(field,value){
	if (!field) return;
	field.disabled=false;
	var changed;
	changed = (field.value!=value);
	field.value=value;
	if (changed)
	{
		try {
			field.onchange();
		}
		catch(err){}
		// acpro 68008 - ra 26.05.2005 - added the invocation of the onchange() event after setting the value, since the display of the region code depends on this
		// note: errors are ignored because not all fields will have an onchange event
	}
}

// AC 28.07.2009 acpro 149037
// Adding  function openwindowinspecifiedtarget and function AutoFormContents
//------------------------------------------------------------------------------
function openwindowinspecifiedtarget (url, targetwindow, sourcesession, newHeight, newWidth, FormToSend, FieldPattern, doNoAutoMove) {
	//if the window to open is a task window, some additional code has to be used
	//SP, 133937, parameter sourcesession added to allow use of multiple DCON sessions
	if (targetwindow=='taskform') {
		if (FormToSend)
		{
			if (url.indexOf('?')==-1)
				url+='?data=';
			else
				url+='&data=';	
			url+=AutoFormContents(document.forms[FormToSend].elements,FieldPattern);
		}

		if (url.indexOf('?')==-1)
			url+='?rnd=' + Math.floor(10000000*Math.random());
		else
			url+='&rnd=' + Math.floor(10000000*Math.random());
	}


	if (isUserActionDenied()) return;
	storeEventSourceObject();
	resetAlreadyResizedFlag();
	self.nowProcessingRequest = 1;
	if (url.indexOf('?')==-1)
		url+='?rnd=' + Math.floor(10000000*Math.random());
	else
		url+='&rnd=' + Math.floor(10000000*Math.random());
	var newWindow;
	resetStatusBar();
	if (doNoAutoMove) {
		newWindow = window.open(url,targetwindow + sourcesession,'scrollbars=yes,toolbar=no,location=no,directories=no,resizable=yes,copyhistory=no,left=40,top=40,width='+newHeight+',height='+newWidth);
	}
	else {
		SetWaitCursor(true);
		newWindow = window.open(url,targetwindow + sourcesession,'scrollbars=yes,toolbar=no,location=no,directories=no,resizable=yes,copyhistory=no,left='+screen.availWidth+',top='+screen.availHeight+',width='+newHeight+',height='+newWidth);
		safeSetFocus(self);
	}
	newWindow.resizeAndPositioningDone = false;
	setTimeout('storeUserActionAllowed()', doubleclickDelay);	
}
//------------------------------------------------------------------------------
function AutoFormContents(elements,nameprefix, excludeField)
{
	var buffer='';
	var encodedData = '';
	if (!excludeField) excludeField='';
	for( var i = 0; i < elements.length; i++ )
	{	
		if (elements[i].type!='button' && elements[i].type!='undefined' && elements[i].name)
		  if (!elements[i].disabled && elements[i].name.substring(0,nameprefix.length) == nameprefix) 
		  { 
			if (elements[i].name.toUpperCase() != excludeField.toUpperCase()){
				if (buffer!='') buffer+='&';
				switch(elements[i].type){
					case 'hidden':
					case 'text':
					case 'textarea':
					case 'select-one':
					  encodedData = EncodeRemoteData(elements[i].value);
					  buffer+=elements[i].name+'='+ encodedData;
					  break;
					case 'radio':
						if (elements[i].checked) {
							encodedData = EncodeRemoteData(elements[i].value);
							buffer+=elements[i].name+'='+ encodedData;
						}
						break;
				}
			}
		}						  						
	}
	
	return buffer;
	
}	
//------------------------------------------------------------------------------

function toggleNotField(linkedControlName, Translated_NOT, Destktop_NOT) {
	var notspanname = 'nc_' + linkedControlName;
	var notspan = document.getElementById(notspanname);
		
	if (notspan.innerHTML.length == '') {
		notspan.innerHTML = Translated_NOT;
		notspan.style.paddingRight = '3px';
		iconformField(Destktop_NOT + linkedControlName).value = '1';
	}
	else {
		notspan.innerHTML = '';
		notspan.style.paddingRight = '0px';
		iconformField(Destktop_NOT + linkedControlName).value = '';
	}
}

