 //blur background and show "loading message"
var resizing = true;

// is this JS executed in Widget or Not
var widget = false;

addResizeEvent(function(){
		return;
		var d = new Date();
		if (!resizing || !singleResize()) return;
		resizing = false;
		setTimeout(enableResize,200);
		fixOverFlow();
	}
);
var wresize = {fired: false, width: 0};
function singleResize(){
	var result = true;
	if (!isIE()) return true;
	if (! wresize.fired) {
        wresize.fired = true;
    }
	 var width = getWindowDimensions().x;
     if ( width != wresize.width ) {
		 //a vertical resize is fired once, an horizontal resize twice
          wresize.width = width;
          return false;

	 }
	return true;
}
function enableResize(){
	resizing = true;
}
//blur background and show "loading message"

addLoadEvent(function(){
	pageLoaded = true;
	hideElement('bgLoading');
	if ((window.blurPage == undefined)) {
		hideElement('bgBlur');
	}
	autoClearMessages(true);
	}
);
function blurBG(show){
	if (show == null) show = true;
	if (show) {
		showElement('bgBlur');
	}else{
		hideElement('bgBlur');
	}
}
function showHelp(id){
		if (id == null) id = helpId;
		var url = contextPath+"/showHelpAction.do?helpId="+id;
		uniquePopUp(url, 1000, 600, 100, 100, 1, 1);
}
function showHelpLink(id){
		if (modalDivs != null && modalDivs.length > 0){
			modalHelpLinkId(id);
		}else{
			showElement('helpLink', "");
			helpId = id;
		}
}
function logOffConfirm(){
	dialog(dict.ARE_YOU_SURE_YOU_WANT_TO_LOGOUT ,function(){	showActivateWindow = false; document.location.href = contextPath+"/userLogoff.do;"; },dict.LOGOFF,"info");
}

//addLoadEvent(function(){checkDebugInfo()});
var debugTimer;
var debugFirstTime = 0;
function checkDebugInfo(firstTime){
	if (!debugMode) return;
	var debugText = getCookie("debug");
	var firstTime = debugFirstTime == 0 ? "firsttime=yes":0;
	submitToUpdate(contextPath+"/debugMode.do","method=display&"+firstTime,"xxxDebug");
	debugTimer = setTimeout('checkDebugInfo();',5*1000);
}
function displayDebug(text){
	showElement('debugHolder');
	if (text == false) $('debugContent').innerHTML = '';
	else
	$('debugContent').innerHTML += text+"<br/>";
}
addLoadEvent(function(){checkSessionExpired(true)});
var sessionExpiredTimer;
var sessionPopUp;
var checkExpiredTimeOut = 0.1; //in minutes
var sessionExpiredShown = false;
var tenantChangedShown = false;
//var sessionCookieName = 'sessionExpired';
if (window.tnName === undefined){
	var tnName = '';
	var userLoginName = '';
}
var loginParams = "justLoggin=true&tenantName="+tnName+"&loginname="+userLoginName;


submitLoginParams = function(){
	submitToUpdate(contextPath+'/userLogonSubmit.do',loginParams+"&refreshDomain=true",'sessionExpiredDiv');
}
loginModalWindow = function(){
	showModalDiv(contextPath+'/index.jsp',loginParams+"&refreshPage=true",'sessionExpiredDiv');
}

changeTenant = function(){
	alert('focuse received');
	var activeTenant = getCookie("sessionFactory");
	var currentTenant = tnName;
	if(currentTenant != activeTenant){
		alert('about to change tenant and submit login');
		submitLoginParams();
	}
}
var origPageTitle = document.title;
function checkSessionExpired(firstTime){
	// checkSessionTimeout defined in inc.js_code.jsp
	if (window.checkSessionTimeout === undefined) return;
	if (isGuestUser) return;
	if (!cookieSupported()) return false;
	currentTenant = tnName;
	activeTenant = getCookie("sessionFactory");
	sessionActive= getCookie('sessionActive');
	//if session is active, check if user is logged to another domain
	if (sessionActive!= null){
		if (activeTenant != null && currentTenant != activeTenant){
			if (! tenantChangedShown && showActivateWindow){

			document.title = "[NOT ACTIVE] " + origPageTitle;
			dialogMessage(dict.THIS_WINDOW_IS_NOT_ACTIVE_ANYMORE /*+ "<br/>"+ dict.YOU_HAVE_BEEN_LOGGED_IN_TO_ANOTHER_DOMAIN*/,
				"Disabled Window", function(){
						submitToUpdate(contextPath+'/userLogonSubmit.do',loginParams+"&refreshDomain=true",'sessionExpiredDiv');
					}, false, "Activate");
				tenantChangedShown = true;
			}
			sessionExpiredTimer = setTimeout('checkSessionExpired();',0.1*1000*60);
			return;
		}


	}
	if (tenantChangedShown){
		//close Modal window
		document.title = origPageTitle;
		closeModal();
	}
	tenantChangedShown = false;
	if (getCookie("ident") != null) {
		//has remmember me cookie
		sessionExpiredTimer = setTimeout('checkSessionExpired();',checkExpiredTimeOut*1000*60);
		return;
	}
    if (sessionExpiredTimer != null){
    	clearTimeout(sessionExpiredTimer);
    }
	if (sessionActive== null){
		//session expired, show modal div if it is not shown
		if (!sessionExpiredShown && !widget){
			showModalDiv(contextPath+'/index.jsp',loginParams,"sessionExpiredDiv",'Login', modalHideCloseLink);

			sessionExpiredShown = true;
			checkExpiredTimeOut = 0.01;
			try{
				if(typeof(wChatBar) != 'undefined'){
					wChatBar.online.onClick();
				}
			}catch(e){
			}
		}
	}else{
		if (sessionExpiredShown){
			closeModals();
			checkExpiredTimeOut = 0.1;
			sessionExpiredShown = false;
			if(typeof(wChatBar) != 'undefined' && wChatBar != null){
				try{
					if(typeof(wChatBar) != 'undefined'){
						wChatBar.offline.onClick();
					}
				}catch(e){
				}
			}
		}
	 sessionExpiredTimer = setTimeout('checkSessionExpired();',checkExpiredTimeOut*1000*5);
	}
}

// GLOBAL METHODS
function showErrorPageDetails( ) {
        $("showDetailsLinkDiv").style.display = "none";
        $("hideDetailsLinkDiv").style.display = "inline";
        $("stackTraceDiv").style.display = "inline";
      }
function hideErrorPageDetails( ) {
        $("showDetailsLinkDiv").style.display = "inline";
        $("hideDetailsLinkDiv").style.display = "none";
        $("stackTraceDiv").style.display = "none";
}
function changeLogOnUser(){
	showModalDiv(contextPath+"/changeUserLogonSubmit.do",'method=prepare','changeUserDiv', dict.LOG_ON_AS_DIFFERENT_USER);
}

function updateUISettings(displayUI, remove, save){
	var params = "displayId="+displayUI;
	var method = "add"
	if (remove) method = "remove";
	if (save) {
		method = "save";
		hideElement("saveDisplaySettings");
	}else{
		showElement("saveDisplaySettings");
	}
	params += "&method="+method;

	submitToUpdate(contextPath+"/updateUI.do",params,'nullDiv');
}

// The correct way of adding a handler to an event without over-riding other handlers.
// Usage: addLoadEvent(nameOfSomeFunctionToRunOnPageLoad); or addLoadEvent( function() { });
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

function addOnResetFormEvent(formId, func) {
	  var form = document.getElementById(formId);
	  if (!form) return;

	  var onreset = form.onreset;
	  if (typeof form.onreset != 'function') {
	    form.onreset = func;
	  } else {
	    form.onreset = function() {
	      if (onreset) {
	        onreset();
	      }
	      func();
	    }
	  }
	}


function tryNowElseOnLoadEvent(code){
	try{
		eval(code);
	}catch(e){
		addLoadEvent(
			function(){
				eval(code);
			}
		)
	}
}



function addResizeEvent(func) {
  var resizeFunct = window.onresize;
  if (resizeFunct != 'function') {
    window.onresize = func;
  } else {
    window.onresize = function() {
      if (resizeFunct) {
        resizeFunct();
      }
      func();
    }
  }
}
function addScrollEvent(func) {
  var scrollFunct = window.onscroll;
  if (typeof scrollFunct != 'function') {
    window.onscroll = func;
  } else {
    window.onscroll = function() {
      if (scrollFunct) {
        scrollFunct();
      }
      func();
    }
  }
}

// add onmousemove function
function addOnMouseMove(func){
	var currentOnMove = document.onmousemove;
	if (typeof document.onmousemove != 'function') {
		document.onmousemove = func;
	} else {
		document.onmousemove = function(e){
			if(currentOnMove){
				currentOnMove(e);
			}
			func(e);
		}
	}
}

function go(url) {
    	location.href = url;
}
function submitByEnter(evt, submitFunction) {
    evt = (evt) ? evt : event;
    var target = (evt.target) ? evt.target : evt.srcElement;
    var form = target.form;
    var charCode = (evt.charCode) ? evt.charCode :
        ((evt.which) ? evt.which : evt.keyCode);
    if (charCode == 13 || charCode == 3) {
        if (submitFunction == null) {
            form.submit();
        }
        else{
        	eval(submitFunction);
        }
        return false;
    }
    return true;
}
function infoStep(goBack){
	new Effect.Fade('infoUpdateDiv');
	var params = goBack != null ? 'previous=true' : '';
	setTimeout("submitToUpdate('"+contextPath+"/showInfoUpdateAction.do','"+params+"','infoUpdateDiv',function(){},function(){new Effect.Appear('infoUpdateDiv', {  from:0.3 });})",1000);;
}

//Creats popup window. 	Parameters "resizable" and "scrollbars" are not obligate.
var uniquePopUpWindow = null;
function uniquePopUp(source, w, h, left, top, resizable, scrollbars){
 if(uniquePopUpWindow == null || uniquePopUpWindow.closed){
    	uniquePopUpWindow = popUp(source, w, h, left, top, resizable, scrollbars);

  	 }else{
    	uniquePopUpWindow.close();
    	uniquePopUpWindow = popUp(source, w, h, left, top, resizable, scrollbars);
  	 };
 }


function popUp(source, w, h, left, top, resizable, scrollbars) {
  var winParameters = "width="+w+", height="+h+", left="+left+", top="+top;
  if (resizable != null) {
  	winParameters += ", resizable="+resizable;
  }
  if (scrollbars != null) {
  	winParameters += ", scrollbars="+scrollbars;
  }
  win = window.open(source, "_blank", winParameters);
  if (win != null) win.focus();
  return win;
}



function refreshPage() {
	document.location.href = document.location.href;
}

/***DOM OPERATIONS*****/
//	Returns children elements of domElement. 	If recursive is true it returns grandchildren also 	tagName specifies tagName of children that should be returned
function deleteChildren(id){
	var element = $(id);
	if (element == null) return;
	while (element.hasChildNodes()){
		element.removeChild(element.firstChild);
	}
}
function checkDiv(divId){
		if ($(divId) != null) return;
		div = document.createElement('div');
		div.id	= divId;
		document.getElementsByTagName('body')[0].appendChild(div);
}
function alternateTable(id, startPos, endPos){
   var table = $(id);
   if (table == null) return;
   var rows = table.rows;
   var start = startPos != null ? startPos : 0;
    var end = (endPos != null && (rows.length - endPos) > start)  ? (rows.length - endPos) : rows.length;

   for(i = start; i < end; i++){
 //manipulate rows
     if( (i-start) % 2 == 0){
       rows[i].className = "even";
     }else{
       rows[i].className = "odd";
     }
   }
   if (endPos == null){
   	 rows[end-1].marginTop = "5px";
   }
   //rows[i].className = "";
}
//  Subtitite two rows from table
function substituteTableRows(sr, dr){
	if (sr == null || dr == null || sr == dr) return;
	var destLength = dr.childNodes.length;
	while (sr.childNodes.length>0){
		var firstElement = sr.removeChild(sr.childNodes[0]);
		dr.appendChild(firstElement);
	}
	for(var i=0;i<destLength;i++){
		sr.appendChild(dr.removeChild(dr.childNodes[0]));
	}

}
function deleteRows(tableId){
	var table = $(tableId);
	if (table == null) return;
	while (table.rows.length > 0){
			table.deleteRow(0);
	}
}
function getChildren(domElement, recursive, tagName, className) {
	if (domElement == null) return;
	var elements = [];
	var tempElements = domElement.childNodes;
	for (var i = 0; i < tempElements.length; i++) {
			var ignoreElement;
			ignoreElement = (tagName != null && (tempElements[i].tagName == null || tagName.toLowerCase() != tempElements[i].tagName.toLowerCase( )));
			if (!ignoreElement)
				ignoreElement = (className != null && (tempElements[i].className == null || tempElements[i].className.indexOf(className) < 0 )) ;

			if (!ignoreElement)
				elements[elements.length] = tempElements[i];
			var grandChildren = [];
			if (recursive) {
				grandChildren = getChildren(tempElements[i], true, tagName, className);
			}
			for (var j = 0; j < grandChildren.length; j++) {
				elements[elements.length] = grandChildren[j];
			}

	}
	return elements;
}
function removeElementInSerializedForm(params, element){

	while (params.indexOf(element+"=") > (-1)){
		var startIndex = params.indexOf(element+"=");
		var subString = params.substring(startIndex, params.length);
		var nextIndex = subString.indexOf("&") > 0 ? subString.indexOf("&") : params.length;
		params =  "" + params.substring(0,startIndex) +""+params.substring(nextIndex+startIndex+1, params.length)
	}
	return params;
}

//messages from messageContaniner and errorContaniner will be automatic removed after specified time
var clearMessagesTimer;
var dontAutoClearMessages = false;

function autoClearMessages(dontDeleteMessages){
	if (dontAutoClearMessages) return;
	if (clearMessagesTimer != null){
		clearTimeout(clearMessagesTimer);
	}
	if (dontDeleteMessages == null){
		 deleteMessages(true);
	}
	//repeat auto clear message after some time
	clearMessagesTimer = setTimeout('autoClearMessages();',10*1000);
}
var autoClearMegCnts = new Array();
 function deleteMessages(noRestart){

 	if (noRestart == null) autoClearMessages(true);
	_deleteDiv($("errorContainer"));
	_deleteDiv($("messageContainer"));
	i = 0;
	if (!(window.modalTitles === undefined)){
		while(i<modalTitles.length){
			_deleteDiv($("modalWindow_"+i+"_errorContainer"));
			_deleteDiv($("modalWindow_"+i+"_messageContainer"));
			if (modalErrors[i] != null) _deleteDiv($(modalErrors[i]));
			if (modalMessages[i] != null) _deleteDiv($(modalMessages[i]));
			i++;

		}
	}
	for ( var i = 0; i < autoClearMegCnts.length; i++) {
		_deleteDiv($(autoClearMegCnts[i]));
		
	}
}
function _deleteDiv(div){
	if (div == null) return;
	while (div.childNodes.length>0){
			div.removeChild(div.childNodes[0]);
	}
}
function writeMessageAutoClear(html, divContainerId){
	writeMessage(html, divContainerId, true, null, true);
	
}
function writeMessage(html, divContainerId, createFocusElement, containerClassName, autoClear){
//	autoClearMessages(true);
	var divElem = $(divContainerId);
	if (autoClear &&  autoClearMegCnts.indexOf(divContainerId)< 0){
		autoClearMegCnts.push(divContainerId);
	}

	if (divElem != null && html != null && html.length > 0) {

		defaultError = divContainerId == "errorContainer";
		defaultMsg = divContainerId == "errorContainer";
		if (defaultError || defaultMsg) {
			if (modalDivs.length > 0){

				if (defaultError){
					newId = modalErrors[modalErrors.length-1];
				}else{
					newId = modalMessages[modalErrors.length-1];
				}
				if (newId == null){
					newId = 'modalWindow_'+(modalDivs.length)+"_"+divContainerId;
				}
				divElem = $(newId);
				html = html.replace("margin: 10px 20%","margin: 0px 8px 0px 8px;");

			}
		}
		if (containerClassName != null){
			divElem.className = containerClassName;
		}
		divElem.innerHTML = html;
		if (html.length < 2) {
			divElem.style.display = "none";
		} else {
			if (containerClassName == null){
				divElem.style.display = "inline";
			}
		}

		if (createFocusElement != null && createFocusElement == true){
			try{
				$(divContainerId+"_focus").focus();
			}catch(e){
			}
		}else{
			var alink = $(divContainerId+"_focus");
			if (alink != null){
				alink.focus();
			}
		}
	}
}
/**      DATA FUNCTION ****/
function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    return true;
}
function getFormElementValue(field, multiField) {
	if (field == null) return;
	if (multiField && field.length != null){
		var value = "";
		for(i=0;i<field.length;i++){
			var fValue = trim(getFormElementValue(field[i]));
			if (fValue == null || fValue.length == 0) continue;
			if (value.length > 0) value+=",";
			value += fValue;
		}
		return value;
	}
	var elem = null;
	if (field.tagName == undefined){
		elem = field[0];
	}else{
		elem = field;
	}
	var tagName = elem.tagName;
	if (tagName == null) return;
	if (tagName.toUpperCase().search(/SELECT/)> -1) return getSelectedValues(field);
	if (tagName.toUpperCase().search(/TEXTAREA/)> -1) return field.value;
	var type = elem.getAttribute("type");
	if (type == null) return;

	if ((type.toUpperCase().search(/CHECKBOX/)> -1) || type.toUpperCase().search(/RADIO/)> -1) {

		return getCheckBoxValue(field);
	}
	var value = "";
	if (field.length != null){

		for(i=0;i<field.length;i++){
			var fValue = trim(field[i].value);
			if (fValue.length == 0 )continue;
			if (value.length > 0) value+=",";
			value += fValue;
		}
		return value;
	}
	return trim(field.value);
}
function setFormElementValue(field, value) {
	if (field == null) return;

	var elem = null;
	if (field.tagName == undefined){
		elem = field[0];
	}else{
		elem = field;
	}
	var tagName = elem.tagName;
	if (tagName == null) return;
	if (tagName.toUpperCase().search(/SELECT/)> -1) return setSelectValues(field,value);
	var type = elem.getAttribute("type");
	if (type != null) {
		if ((type.toUpperCase().search(/CHECKBOX/)> -1) || type.toUpperCase().search(/RADIO/)> -1) {
			return setCheckBoxValue(field, value);
		}
	}
	return field.value = value;
}
function appendTextArea(id, text){
		var obj=$(id);
		if(!isIE()){
			var start=0;
			start=obj.selectionStart;
			var end=0;
			end=obj.selectionEnd;
			var text1=obj.value.slice(0,start);
			var text2=obj.value.slice(end);
			var result = text1 + text + text2;
			obj.value=result;
		}else{
			obj.focus();
			var range=document.selection.createRange();
			if(range.parentElement() !=obj)
				return false;
			range.text=text;
		}

}
/**CHECK BOXES, RADIO BUTTON METHODS****/
//Change value of CHECK_BOXES, RADIO (end boolean properties)
function getCheckBoxValue(checkbox) {
	if (checkbox == null) return null;
	var result = null;
	if (checkbox.length != null){
		for(var i=0;i<checkbox.length;i++){
			if (checkbox[i].checked){
				if (result == null) {result = checkbox[i].value;}
				else {result+= ","+checkbox[i].value;}
			}
		}
	}else{
		return checkbox.checked ? checkbox.value : null;
	}
    return result;
}
//checkbox is html element (retreived by form.elements['']
function setCheckBoxValue(checkbox,value) {
	if (checkbox == null || value==null) return;
	var values = value.split(',');
	for(var i=0;i<checkbox.length;i++){
		if (values.indexOf(checkbox[i].value) > -1){
			checkbox[i].checked = true;
		}
	}
}
function setCheckBoxAll(checkbox, value) {
	if (checkbox == null) return;
	for(var i=0;i<checkbox.length;i++){
			checkbox[i].checked = value != null && value == true;
	}
}
function selectFormAllCheckBox(formName, value) {
	var form = document.forms[formName];
	if (form == null) return;
	for(var i=0;i< form.length; i++){
		var elem = form[i];
		if( elem.type != null && elem.type == 'checkbox')
		elem.checked = value;
	}
}
//disable or enable array of checkbox-es
function disableCheckBoxValue(checkbox, value) {
	if (checkbox == null || value == null) return;
	for(var i=0;i<checkbox.length;i++){
		checkbox[i].disabled = value;
	}
}
function createCheckBox(id, value, labelText, checked) {
	var checkbox = document.createElement('input');
	checkbox.setAttribute('type','checkbox');
	checkbox.id = id;
	checkbox.value = value;
	checkbox.checked = checked;
	var label = document.createElement('label');
	label.setAttribute('for', id);
	label.appendChild(checkbox);
	label.appendChild(document.createTextNode(labelText));
	return label;
}
function reverseFormProperty(formName, propertyName) {
	var form = document.forms[formName];
	var boolProperty = form.elements[propertyName];
	boolProperty.value = !boolProperty.value;
}
/* Creates checkbox Element with procedeed name, on_change_function and default Value*/
function makeCheckBox(name, onChangeFunc, checked) {
	var checkBox = document.createElement('INPUT');
	checkBox.setAttribute('type', 'checkbox');
	checkBox.setAttribute('id', name);
	checkBox.name = name;
	if (onChangeFunc != null)
		checkBox.onchange = onChangeFunc;
	if (checked != null && (checked == true || checked != 0)) {
		checkBox.checked = true;
	}
	return checkBox;
}
//if checkbox is true, element is enabled
function checkboxEnableElement(checkbox, element){
	if (checkbox == null || element == null) return;
	if (checkbox.checked) element.disabled = false;
	else element.disabled = true;
}
/***SELECT BOX FUNCTIONS ***/
/* Selects all options of specified select box. */
function resetAll(selectBox) {
    for (var i = 0; i < selectBox.length; i++) {
        selectBox.options[i].selected = false;
    }
}
function selectAll(selectBox) {
    for (var i = 0; i < selectBox.length; i++) {
        selectBox.options[i].selected = true;
    }
}
//copy from source optionBox to destination Option Box
function copySelectBox(srcOptionBox, destOptionBox){
	if (srcOptionBox == null || destOptionBox == null) return;
	 deleteAllSelectOptions(destOptionBox);
	for (var i = 0; i < srcOptionBox.options.length; i++) {
		destOptionBox.options[i] = new Option(srcOptionBox.options[i].text, srcOptionBox.options[i].value);
	}

}
/* Returns array with values of selected option boxes. Very usefull for multiply select boxes   */
function getSelectedBoxValues(selectBox) {
	var indexes = new Array();
	if (selectBox){
	    for (var i = 0; i < selectBox.length; i++) {
	        if (selectBox.options[i].selected == true){
	        	indexes[indexes.length] = selectBox.options[i].value;
	        }
	    }
	}
    return indexes;
}
function setSelectValues(selectBox,value) {
	if (selectBox == null || value==null) return;
	var values = value.split(',');
    for (var i = 0; i < selectBox.length; i++) {
        if (values.indexOf(selectBox.options[i].value) > -1){
        	selectBox.options[i].selected =true;
        }else{
			selectBox.options[i].selected =false;
		}
    }
}

function setSelectionByText(selectBox, text) {
	if (!selectBox || !text) return;
    for (var i = 0; i < selectBox.length; i++) {
        if (selectBox.options[i].text == text){
        	selectBox.options[i].selected =true;
        }else{
			selectBox.options[i].selected =false;
		}
    }
}

//copy source array(Integer[], String[] ) to destination Option Box
function copySelectBoxFromArray (srcArray, destOptionBox) {
	if (srcArray == null || destOptionBox == null) return;
	 deleteAllSelectOptions(destOptionBox);
	 for (var i = 0; i < srcArray.length; i++) {
		destOptionBox.options[i] = new Option(srcArray[i], srcArray[i]);
	}
}

/* optionArray should be array of Option objects.*/
function makeSelectBox (name, optionArray, defaultSelected) {
	var selectBox = document.createElement('SELECT');
	selectBox.name = name;
	selectBox.id = name;

	for (var i = 0; i < optionArray.length; i++) {
		selectBox.options[i] = new Option(optionArray[i].text, optionArray[i].value);
		if (defaultSelected != null && selectBox.options[i].value == defaultSelected) {
			selectBox.selectedIndex = i;
		}
	}
	if (defaultSelected == null) {
		selectBox.selectedIndex = 0;
	}
	return selectBox;
}
function changeSelectOption(selectBox, optionIndex, newValue, newText) {
	var newOption;
	if (newText == null)
		newOption = new Option(newValue, newValue);
	else
		newOption = new Option(newValue, newText);
	selectBox.options[optionIndex] = newOption;
}
function getFieldIndexInOptions(value, options) {
	var fieldIndex = -1;
	for (var i = 0; i < options.length; i++) {
		if (options[i].value == value) {
			fieldIndex = i;
			break;
		}
	}
	return fieldIndex;
}
//remove all options from select box
function deleteAllSelectOptions(selectBox){
	var i;
	while(selectBox.length>0){
		deleteSelectOption(selectBox,0);
	}
}
//delete 'optionIndex' option box in select box
function deleteSelectOption(selectBox, optionIndex) {
	selectBox.options[optionIndex] = null;
}
//search option in select box by value. Return index of founded option or -1
function getFieldIndexFromSelectBox(selectBox, value) {
	if (selectBox == null || selectBox.options == null) return;
	for (var i = 0; i < selectBox.options.length; i++) {
		if (selectBox.options[i].value == value)
			return i;
	}
	return -1;
}
//search selected option in select box by value(used for multiple select box). Return index of founded option or -1
function getValueSelectedFromSelectBox(selectBox, value) {
	if (selectBox == null || selectBox.options == null) return;
	for (var i = 0; i < selectBox.options.length; i++) {
		if (selectBox.options[i].value == value && selectBox.options[i].selected)
			return i;
	}
	return -1;
}
//if select box has selected option return true
function isSelectedSelectBox(selectBox) {
    for (var i = 0; i < selectBox.length; i++) {
        if  (selectBox.options[i].selected){
        	return true;
        }
    }
    return false;
}
//unselect all options in select box
function unSelectAllSelectBox(selectBox) {
	if (!selectBox) return;
    for (var i = 0; i < selectBox.length; i++) {
        selectBox.options[i].selected = false;
    }
}
//unselect all options in select box
function addOptionInMultiBox(table, value, text) {
	if (table == null || value == null || text == null) {return }
	var newRow = table.rows[table.rows.length-2].cloneNode(true);
	var children = getChildren(newRow, true);
	var oldValue = getChildren(newRow, true, "input");
	if (oldValue.length > 0) oldValue = oldValue[0].value;
	var attrs = ["id","value","for","onmouseover"];
	var td, tdEvent;
	for(var i=0;i<children.length;i++){
		child = children[i];
		if (child != null && child.nodeType != 3){
			if (child.tagName != null && child.tagName.toLowerCase() == "label"){
				child.innerHTML = text;
			}

			for(var j=0;j<attrs.length;j++){

				var attValue = child.getAttribute(attrs[j]);

				if (attValue != null){
					var newValue = ""+attValue;
					while (newValue.indexOf(oldValue) > -1) {
						newValue = newValue.replace(oldValue,value);
					}
					if (attrs[j].toLowerCase() == "onmouseover") {
						td = child;
						tdEvent = new Function(newValue);
					}else{
						child.setAttribute(attrs[j], newValue);
					}

				}
			}
		}
	}
	var tbody = table.getElementsByTagName('tbody')[0];
	tbody.insertBefore(newRow, tbody.firstChild);
	newRow.removeChild(td);
	cell = newRow.insertCell(2);
	if (tdEvent != null) EventUtil.addEventHandler(cell,"mouseover",tdEvent);
	cell.innerHTML = td.innerHTML;
	//newRow.innerHTML = text;
	//table.insertRow(table.rows.length-1).innerHTML = text;

	//newRow.focus();
}
function addOptionInSortedSelectBox(selectBox, value, text, startIndex) {
	if (selectBox == null || value == null || text == null) return;
	var tempOption;
	var index = selectBox.length - 1;
	var start = startIndex != null ? startIndex : 0;
    for (var i = start; i < selectBox.length; i++) {
        if (selectBox.options[i].text.toLowerCase() >	text.toLowerCase() ){
        	index = i;
        	break;
        }
    }
    tempOption = selectBox.options[index];
    selectBox.options[index] = new Option(text, value);
    selectBox.options[selectBox.length] = tempOption;
}
function addNewOption(selectBox, value, text){
	if (selectBox == null || value == null || index == null) return;
	selectBox.options[selectBox.length] = new Option(text, value);
}
function compareOptions(a, b) {
    var firstValue = a.value.toLowerCase( );
    var secondValue = b.value.toLowerCase( );
    if (firstValue < secondValue) {return -1}
    if (firstValue > secondValue) {return 1}
    return 0;
}
// Finds all select boxes on page, and scroll them  down to last option which is selected.  Usage:: addLoadEvent(showSelectedInSelectBox);
function showSelectedInSelectBox(){
	var selectElements = document.getElementsByTagName("select");
	for (var i = 0; i<selectElements.length; i++){
		options = selectElements[i].options;
		var lastSelected = -1;
		for (var j=0; j<options.length; j++){
			if (options[j].selected){
				lastSelected = j;
			}
		}
		if (lastSelected != -1){
			options[lastSelected].selected="selected";
		}
	}
}
//For multiply select box,check if default index is selected. If default value is selected, function deselect all other selected options
function selectDefaulValueInSelectBox(optionBox, index){
   		if (optionBox == null) return null;
   		if (index == null) index = 0;
		if (optionBox.options[index].selected == true || (isSelectedSelectBox(optionBox) == false)){
			unSelectAllSelectBox(optionBox);
			optionBox.options[index].selected = true;
		}
   }
 //Get selected value(s) of select box. For multiply select box, values are separeted by delimiter (, is default);
function getSelectedValues(selectBox, delimiter){
		return _getSelectedTextValue(true,selectBox, delimiter);
 }
 function getSelectedText(selectBox, delimiter){
		return _getSelectedTextValue(false,selectBox, delimiter);
 }
 function _getSelectedTextValue(useValue, selectBox, delimiter){
		if (selectBox == null || selectBox.options == null) return null;
		var del = delimiter != null ? delimiter : ',';
   		var result = "";
   		for (var i = 0; i < selectBox.length; i++) {
	        if (selectBox.options[i].selected == true){
	        	if (result.length > 0) result += del;
	        	var v = useValue ? selectBox.options[i].value : selectBox.options[i].text;

				result += v;
	        }
		}
		return result;
 }
//In html div element, provided by id, write down a number of selected items in multiply select box
function refreshOptionInfo(selectBox,divId){
		var values = getSelectedBoxValues(selectBox);
		var size = (values.length == 1 && values[1] == "") ? 0 : values.length;
   		updateInfoTag(size, divId);
}
//display number of select boxes in div.
function refreshCheckBoxInfo(boxes,divId){
		var size = 0;
		if (boxes == null) return;
		for(var i=0;i<boxes.length;i++){
			if (boxes[i].checked) size++;
		}
   		updateInfoTag(size, divId);
}
//see refreshCheckBoxInfo(boxes,divId)
function updateInfoTag(items, divId){
	if (items > 1){
   			writeMessage(items+' items selected', divId);
   		}else if (items == 1){
   			writeMessage(items+' item selected', divId);
		}else{
			writeMessage(" ", divId);
		}
}

//enable all froms
function enableForms(){
	var allForms = document.getElementsByTagName("form");
	for(var i=0; i < allForms.length; i++){
		var formEl = allForms[i];
		Form.enable(formEl);
	}
}

/****POSITIONING METHODS*****/
/*Returns x position relative to window left edge. */
	function findPosX(obj){
	var pos = findPosition(obj);
		return pos.x;
	}
/* 	Returns y position relative to window top edge.*/
	function findPosY(obj){
		var pos = findPosition(obj);
		return pos.y;
	}
/* 	Returns x and y postions of object (includin offset)*/
	function findPosition(obj){
		var curleft = 0;
		var _object = obj;
		if (obj.offsetParent){
			while (obj.offsetParent){
				curleft += obj.offsetLeft
				obj = obj.offsetParent;
			}
		}
		else if (obj.x) curleft += obj.x;
		var curtop = 0;
		obj = _object;
		if (obj.offsetParent){
			while (obj.offsetParent){
				curtop += obj.offsetTop
				obj = obj.offsetParent;
			}
		}
		else if (obj.y) curtop += obj.y;
		return {x: curleft, y: curtop};
	}

	var IE = document.all ? true : false;
	if (!IE) document.captureEvents(Event.MOUSEMOVE)
	var mouseXY = {x: 0, y:0};
	function getMouseXY(e) {
		if (IE) { // grab the x-y pos.s if browser is IE
			var evnt = e || window.event;
			var docElement = document.documentElement,
		     body = document.body || { scrollTop: 0 };
			tempX = evnt.clientX + (docElement.scrollLeft || body.scrollLeft) - (docElement.clientLeft || 0);
			tempY = evnt.clientY + (docElement.scrollTop || body.scrollTop) - (docElement.clientTop || 0);
		}
		else {  // grab the x-y pos.s if browser is NS
			tempX = e.pageX;
			tempY = e.pageY;
		}
		if (tempX < 0){tempX = 0;}
		if (tempY < 0){tempY = 0;}
		mouseXY = {x: tempX, y: tempY};
		return {x: tempX, y: tempY};
	}
	addOnMouseMove(getMouseXY);
	function getWindowDimensions(){
		if ( typeof( window.innerWidth ) == 'number' ) {
	        bgWidth  = window.innerWidth;
			bgHeight  = window.innerHeight;
	    } else if ( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
	        bgWidth  = document.documentElement.clientWidth;
			bgHeight  = document.documentElement.clientHeight;
	    } else if ( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
	        bgWidth = document.body.clientWidth;
			bgHeight  = document.body.clientHeight;
	    }
		windowXY = {x: bgWidth, y: bgHeight};
		return windowXY;
	}
/** AJAX SUPPORT METHODS    ***/
	function submitValidateFormWithMethod(formName, successDiv, method, dontDisable, additionalParams){
		var validForm = validator.find(formName);
		if (validForm == null) {  return alert('validation form is not found');};
		if(!validForm.validate()) return;
		var params = validForm.updatedElemsQuery();
		if(typeof additionalParams != 'undefined' && additionalParams != null && params!=null ){
			params = params + additionalParams;
		}
		submitFormWithMethod(formName, successDiv, method, null, null, dontDisable, params);
	}
	function submitValidateWithMethod(form, successDiv, method, dontDisable, additionalParams){
		var validForm = validator.find(form.id);
		if (validForm == null) {  return};
		if(!validForm.validate()) return;
		var params = validForm.updatedElemsQuery();
		if(typeof additionalParams != 'undefined' && additionalParams != null && params!=null ){
			params = params + additionalParams;
		}
		submitWithMethod(form, successDiv, method, null, null, dontDisable, params);
	}
	//deserialize form but doesn't disable form attributes while waiting for respond
	//validate : if form has been initialized in validator and validation failed, return;
	function submitEnabledForm(formName, successDiv, method, modalWindow, validate){
		if (validate){
			var validForm = validator.find(formName);
			if (validForm != null && !validForm.validate()) {
				displayingModal = 0;
				return;
			}
		}
		submitFormWithMethod(formName, successDiv, method, null, null, true, null, modalWindow);
	}
	//creates modal dialog with "Yes" and "No". If user press yes, "submitFormWithMethod" is executed with provided params
	function modalSubmitWithMethod(text, title, formName, successDiv, method, loadingFunc, completeFunc, notDisable){
		dialog(text,function(){
			submitFormWithMethod(formName, successDiv,method,loadingFunc,completeFunc,notDisable);}, title, 'dialog');
	}
	//serialize formName and create AJAX request with form attributes as parameters. Method is used for method handler for Struts dispath actions.
	//loadingFunc is executing before and completeFunc after receiving data from server
	function submitFormWithMethod(formName, successDiv, method, loadingFunc, completeFunc, notDisable, addedParams, modalWindow) {
		_submitMethodWithMethod(null, formName, successDiv, method, loadingFunc, completeFunc, notDisable, addedParams, modalWindow)
	}
	function submitWithMethod(form, successDiv, method, loadingFunc, completeFunc, notDisable, addedParams) {
		_submitMethodWithMethod(form, null, successDiv, method, loadingFunc, completeFunc, notDisable, addedParams)
	}

	function _submitMethodWithMethod(formObj, formName, successDiv, method, loadingFunc, completeFunc, notDisable, addedParams, modalWindow) {

		var form = formObj != null ? formObj : document.forms[formName];

		if (method != null && form != null && form.elements['method'] != null){
			form.elements['method'].value = method;
		}
		if (form  == null) return;
		var params = Form.serialize(form);
		var url = form.action;
		//disable form
		if (null == notDisable ) {

			try{
				Form.disable(form);
			}catch(e){
			}
		}
		if (modalWindow == null){
			modalWindow = false;
		}
		submitToUpdate(url, params, successDiv, loadingFunc, completeFunc, modalWindow, addedParams);
	}
	//creates modal dialog with "Yes" and "No". If user press yes, "submitFormWithMethod" is executed with provided params
	function modalSubmitToUpdate(text, header, url, params, successDiv, loadingFunc, completeFunc){
		dialog(text,function(){submitToUpdate(url, params,successDiv,loadingFunc,completeFunc);});
	}

	//modalWindow (null or true) - all modal divs will be closed.
	function submitToUpdate(url, params, successDiv, loadingFunc, completeFunc, modalWindow, addedParams) {
		var preAction, postAction;
		if (loadingFunc == null) {
			preAction = function() {
				showLoading();
				//blurBG(true);
			}
		}else{
			preAction = function() {
				showLoading();
				//blurBG(true);
				loadingFunc();
			}
		}
		if (completeFunc == null) {
			postAction = function() {
				hideLoading(500);
				//blurBG(false);
			}
		}else{
			postAction = function() {
				hideLoading(500);
				completeFunc();
				//blurBG(false);
			}
		}
		if (modalDialogFlag != null && (modalWindow != null && modalWindow == true)) {
			emptyModal();
			 postAction = function() {
				displayingModal = 0;
				hideLoading(500);
				showModal(successDiv);
				completeFunc();
			}
		}
		checkDiv(successDiv);
		showElement(successDiv); //niksa
		// showHideElement(successDiv);
		if (!(window.tnName === undefined)) {
			params += '&tenantName='+tnName;
		}

		if(typeof window.widget != 'undefined' && window.widget == true){
			params += '&widget=true';
		}
		if (addedParams != null){
			params += "&"+addedParams;
		}
		// removing existing messages

		//alert(url+"; params="+params+"; successDiv="+successDiv);
		var ajax = new Ajax.Updater(
			{success: successDiv},
			url,
			{method: 'post', parameters: params, encoding:'UTF-8',evalScripts: true,
			 onComplete: postAction, onLoading: preAction});
		return ajax;
	}

	function showLoading(){
		//document.body.className = "progCursor";
		document.body.style.cursor ='progress';
		var links = document.links;
		for (var i=0; i<links.length; i++)
			links[i].style.cursor="progress";
	}

	function hideLoading(time){
		//setTimeout('document.body.className = ""' , time);
		setTimeout("document.body.style.cursor ='default';var links = document.links; for (var i=0; i<links.length; i++) links[i].style.cursor='pointer'; ",
				time);
	}

	function replaceLinksWithSubmitUpdate(urlText,paramText,baseUrl,baseParams,successDiv,ignoreParams){
		for (i = 0; i < document.links.length; i ++) {
			var link = document.links[i];
			var linkText = link.href;
			if (linkText.indexOf(urlText) != -1 && linkText.indexOf(paramText) != -1) {
				var parameters = linkText.substring(linkText.lastIndexOf('?')+1,linkText.length);
				if (baseParams != null) parameters +='&' + baseParams;
				if (ignoreParams != null && parameters.indexOf(ignoreParams) != -1) continue;
				 link.href  = "javascript://nop/";
				var functionDef = "submitToUpdate('"+contextPath+baseUrl+"','"+parameters+"','"+successDiv+"');";
				var eventHandler = new Function(functionDef);
				EventUtil.addEventHandler( link,"click",eventHandler);
			}
		}
	}
	//replace all links in DOM that contains urlText and contains paramText with function. Function will use query parameters as function parameters
	//it is used to make displatable ajax-olic
	function replaceLinksWithFunction(urlText,paramText,functionName, badParam){
		for (i = 0; i < document.links.length; i ++) {
			var link = document.links[i];
			var linkText = link.href;
			if (linkText.indexOf(urlText) != -1 && (paramText == null || linkText.indexOf(paramText) != -1)) {
				if (badParam != null && linkText.indexOf(badParam) != -1) continue;
				var parameters = linkText.substring(linkText.lastIndexOf('?')+1,linkText.length);
				 link.href = "javascript:"+functionName+"('"+parameters+"');";
			}
		}
	}

/**          START EFFECT SUPPORT     ***/
	function disableForm(formName,disable) {
		var f = document.forms[formName];
		if (disable != null && disable == true && f != null){
			Form.disable(f);
		}else if (f != null){
			Form.enable(f);
		}
	}
	//toggle element
	function showHideElement(id, displayAttribute){
		var element = $(id);
			if (element == null) return;
			if (element.style.display != 'none'){
				hideElement(id);
			}else{
				showElement(id, displayAttribute)
		}
	}
	//element id ; set  toShow =false for hiding element(otherwise is shown)  and display attribute when element is show (block is default)
	function showHide(id, toShow, displayAttribute){
		if (toShow != null && toShow == false){
			hideElement(id);
		}else{
			showElement(id, displayAttribute);
		}
	}
	function hideElement(id){
		element = document.getElementById(id);
		if (element== null) return;
		element.style.display = 'none';
	}
	function showElement(id, displayAttribute){
		var display = displayAttribute != null ? displayAttribute : 'block';
		element = document.getElementById(id);
		if (element == null) return;
		element.style.display = display;
	}
	function toggleEditForm(divId, formName) {
				blind(divId);
	}
/** Notification Email JS Support     ***/
	function addEmailAddress(boxId, otherBoxId){
		var obj = $(boxId);
		if ((obj.options[0] != null) && (obj.options[0].value == "") ){
			obj.options[0] = null;
		}
		var oName = $("newNotificationName");
		var newName = trimCh(oName.value, " ");
		newName = newName.replace("<", "&lt;");
		newName = newName.replace(">", "&gt;");
		var oEmail = $("newNotificationEmail");
		var newEmail = trimCh(oEmail.value, " ");
		if (newName=="" && newEmail=="")
			return false;
		if (!isEmailAddress(newEmail)) {
			alert(newEmail + " " + dict.IS_NOT_VALID_EMAIL_ADDRESS);
			return false;
		}

		var txt = trimCh(newName + " <" + newEmail + ">", " ");

		var len = obj.length;
		for ( var i = (len -1); i>=0; i--){
			if (txt == obj.options[i].value ) {
				alert(txt + " "+ dict.IS_ALREADY_IN + " " + obj.name+ ". "+ dict.YOU_CANT_ADD_ONE_EMAIL_ADDRESS_MORE_THEN_ONCE);
				return false;
			}
		}

		var obj1 = $(otherBoxId);
		var len1 = obj1.length;
		for ( var i = (len1 -1); i>=0; i--){
			if (txt == obj1.options[i].value ) {
				alert(txt + " " + dict.IS_ALREADY_IN + " " + obj1.name + ". "+dict.ONE_EMAIL_ADDRESS_CANT_BE_IN_EMAILS_AND_EXCLUDEDEMAILS_IN_THE_SAME_TIME);
				return false;
			}
		}

		var len1 = obj.length;
		obj.options[len1] = new Option(txt);
		obj.options[len1].value = txt;
		oName.value = "";
		oEmail.value = "";
	}

	function removeEmailAddress(boxId){
		var obj = $(boxId);
		var len1 = obj.length;
		for ( var i = (len1 -1); i>=0; i--){
		if (obj.options[i].selected == true ) {
			obj.options[i] = null;
			}
		}
	}

	//used for notifications in action
	var emailHolder = new Array();
	emailHolder.push('additionalNotif_1');
	emailHolder.push('additionalNotif_3');
	emailHolder.push('additionalNotif_2');
	function copyEmails(param) {
		var suffix = param != null ? "_"+param : '';
		var s = $( 'additionalNotif'+suffix ).value;
		for( var i=0; i < $( 'userSelectMail' ).length; i++ ) {
			if( $( 'userSelectMail' ).options[i].selected &&
				$( 'userSelectMail' ).options[i].value != "" &&
				!containInArray( emailHolder, $( 'userSelectMail' ).options[i].value ) ) {
				s = s + $( 'userSelectMail' ).options[i].value + ",\n";
			}
		}
		$( 'additionalNotif'+suffix ).value = s;
	}
	function containInArray( arr, v) {

		if (arr == null) return false;
		for(var i=0;i<arr.length;i++){
			var elem = $(arr[i]);
			if( elem != null && elem.value.indexOf( v ) != -1 ) {
				return true;
			}
		}
		return false;
	}

// parent - child select box control for custom fields
function setParentByChildValue(fieldPrefix){
	var selectBox = $(fieldPrefix+'_data');
	var value = selectBox.value;
	if (value == null) return;
	var parId;
	for (var i = 0; i < selectBox.options.length; i++) {
		if (selectBox.options[i].value == value){
			parId =  selectBox.options[i].getAttribute('parId');
			break;
		}
	}
	updateChildBoxValue(parId, fieldPrefix);
	setSelectValues($(fieldPrefix+'_parent'),parId);
	setSelectValues($(fieldPrefix),value);
}
function updateChildBox(parentBox, fieldPrefix){
	updateChildBoxValue(parentBox.value, fieldPrefix);
}
function updateChildBoxValue(value, fieldPrefix){
	var dataBox = $(fieldPrefix+'_data');
	var selectAll = false;
	if (value == null || value == -1 || value =="") selectAll = true;
	var boxData = new Array();
	for (var i = 0; i < dataBox.length; i++) {
		var parId = dataBox.options[i].getAttribute('parId');
        if ((parId != null && parId == value)|| selectAll){
        	boxData[boxData.length] = dataBox.options[i].value;
			boxData[boxData.length] = dataBox.options[i].text;
        }
    }

	var sonBox = $(fieldPrefix);
	deleteAllSelectOptions(sonBox);
	sonBox.options[0]  = new Option("--select--","");

	for (var i = 0; i < boxData.length; i = i+2) {
		sonBox.options[sonBox.length] = new Option(boxData[i+1], boxData[i]);
	}
}
// end parent - child select box control for custom fields

function escapeAll(value){
	if (value == null) return;
	// value = escape(value);
	 value = value.replace(/\//g,"%2F");
     value = value.replace(/\?/g,"%3F");
     value = value.replace(/=/g,"%3D");
     value = value.replace(/&/g,"%26");
     value = value.replace(/@/g,"%40");
	 value = value.replace(/\+/g,"%2B");
	 value = value.replace(/"/g,"%22");
	 value = value.replace(/'/g,"%27");
	 value = value.replace(/\r\n/g,"%0A");
	 value = value.replace(/\n/g,"%0A");
	 value = value.replace(/\r/g,"%0A");

	 return value;
}
function unEscapeAll(value){
	if (value == null) return;
	 //value = unescape(value);
	 value = value.replace(/%2F/g,"/");
     value = value.replace(/%3F/g,"?");
     value = value.replace(/%3D/g,"=");
     value = value.replace(/%26/g,"&");
     value = value.replace(/%40/g,"@");
	 value = value.replace(/%2B/g,"+");
	 value = value.replace(/%22/g,"\"");
	 value = value.replace(/%27/g,"'");
	 value = value.replace(/%0A/g,"\n");

	 return value;
}
function removeDoubleLine(obj) {
   var str = obj.value;
   while(str.indexOf("\n\n") >= 0) {
      str = str.replace(/\n\n/g, "\n");
   }
   obj.value = str;
}
function randomString(length) {
	if (length == null) return null;
	var chars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz0123456789";
	var randomstring = '';
	for (var i=0; i<length; i++) {
		var end = i == 0 ? 51:chars.length;
		var rnum = Math.floor(Math.random() * end);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}
function reduceString(text, length) {
	if (text == null || length == null) return text;
	return text.length < length ? text : text.substring(0, length-3) + '...';
}
var overFlowDivs = null;
//div-id set overflow for particular element. If null, ali divs are considering
//assocDivId - if setting overflow depends on some other div ( can be true)
function fixOverFlow(divId, assocDivId, overflowY){
		 var addDiv2Array = overFlowDivs == null || divId != null;
		 if (addDiv2Array){
			if (overFlowDivs == null) overFlowDivs = new Array();
		 }
		 var all;
		 var i = 0;
		 if (divId != null){
			i = 1;
			all = new Array();
			if ($(divId) != null) {
				all.push($(divId));
			}else{
				return;
			}


		 }else if (overFlowDivs != null && overFlowDivs.length > 0){
			//if overflow is called for all divs, don't iterate through all, just check them from array
			all = overFlowDivs;
			i = all.length;
		 }else{
			all = document.getElementsByTagName('div');
			i = all.length;
		 }
		  var width = null;
 		  var win = getWindowDimensions();

		  while (i--) {
		  	var overflow = all[i].getAttribute('overflow');
			if (overflow == null) continue;
			overflow = trim(overflow);
			var overFlowAttrs = overflow.split(",");
			var parentDiv = null;
			if (overflow.indexOf("parent")>-1){
				var pid = getValueFromOverflow(overFlowAttrs, "parent")
				parentDiv = $(pid);
			}
			if (parentDiv != null){
				var parentHidden = 'none' == parentDiv.style.display;
				if (!parentHidden && overflow.indexOf("rel")>-1){
					var relValue = getValueFromOverflow(overFlowAttrs, "rel")
					width = win.x - parseFloat(relValue);
				}
				if (parentHidden  && overflow.indexOf("margin")>-1 ){
					minValue = getValueFromOverflow(overFlowAttrs, "margin");
					if (minValue != null){
							minValue = parseFloat(minValue);
							width = win.x-minValue;
					}
				}
				if (width == null) {
					width = win.x;
				}
			}else{
				if (overflow.indexOf("px") > -1){
					//overflow in pixels
					overflow = overflow.substring(0, overflow.length-2);
					var relValue = parseFloat(overflow);
					width = win.x - parseFloat(relValue);
				}else{
					//overflow in percentage
					overflow = overflow.substring(0, overflow.length-1);
					width = win.x * parseFloat(overflow);
				}
			}
			all[i].style.width = width+"px";

			if (addDiv2Array){
				if ((overFlowDivs.indexOf(all[i])) < 0){
					overFlowDivs.push(all[i]);
				}
			}
		    if (all[i].scrollWidth > all[i].offsetWidth || overflowY) {
			  if (!IE){
				   //ff
				  all[i].style['overflow'] = 'auto';
			  }else{
				   //ie

				  all[i].style['paddingBottom'] = '20px';
				  all[i].style['overflowY'] = 'hidden';


			  }
		    }
		}
	}
function getValueFromOverflow(overFlowAttrs, name){
	var value = null;
	for(var j=0;j<overFlowAttrs.length;j++){
		if (overFlowAttrs[j].indexOf(name) > -1)value = overFlowAttrs[j];
	}
	if (value != null) return value.split(":")[1];
}
/* lnikolic 2008-08-13, ova funkcija je iskopirana sa search_content.jsp strane */
	function setDisplayType(selectedViewType, formName){
		var form = document.forms[formName];

		if (selectedViewType != null){
			form.view.value = selectedViewType;
		}
		else{
			form.view.value = 0;
		}
	}

/* can work on home page, but still not implemented for the search page.*/
/* lnikolic, 2008-09-08, used to determine size of a chart*/
function evaluateChartWith(){
		if (screen.width > 1280){
			return 600;
		}
		else {
			return parseInt(screen.width * 0.46);
		}
	}

	function evaluateChartHeight(){
		if (screen.height > 1024){
			return 500;
		}
		else {
			return  parseInt(screen.height * 0.46);
		}
	}

	function isNumberKey(evt){
		 var charCode=(evt.which) ? evt.which : event.keyCode
                    if(charCode > 31 && (charCode <48 || charCode>57) && charCode != 46)
                        return false;
                    return true;
    }

	// Removes initial (leading) chars ch from string s.
	function lTrimCh (s,ch)	{
		var i;
		if (s == null) return "";
	    for(i=0;i<s.length && s.charAt(i)==ch;i++);
	    return s.substring (i, s.length);
	}
	// Removes trailing chars ch from s.
	function rTrimCh (s,ch)	{
		var i;
		if (s == null) return "";
	    for(i=s.length-1;i>=0 && s.charAt(i)==ch;i--);
	    return s.substring (0,i+1);
	}

	// Removes initial (leading) ch and ending ch chars from s.
	function trimCh(s,ch){
	    return rTrimCh(lTrimCh(s,ch),ch);
	}
	function trim(s){
	    return trimCh(s,' ');
	}

/**
 * Disable all links with specified value of class attribute.
*/
function disableLinks(className){
	var links = document.getElementsByClassName(className);
	if (!links) return;
	for (var i=0; i<links.length; i++){
		if (links[i].nodeName=='A' || links[i].nodeName=='a'){
			links[i].setAttribute('href', '#');
			links[i].onclick = function(){
				return false;
			};
			links[i].setAttribute('target', '');
		}
	}
}
function disableNonSimpleUI(){

	var links = document.getElementsByClassName('notSimpleUI');
		for (var i=0; i<links.length; i++){
		hideElement(links[i]);
	}
}

function searchByLetter(formName,letter,onClick){
	var inputParameters = null;
	var form= document.forms[formName];
	selectFormAllCheckBox(formName,false);
	form.elements['phrase'].value=letter;
	form.elements['fields[0].name'].checked=true;
	eval(onClick);
}
function searchFilterListRefresh(inputParameters){
	searchFormRefresh('SearchFilter','SearchFilterListDiv',inputParameters,null, 'SearchFilterForm');
}
function searchAccountListRefresh(inputParameters){
	var tableParams = urlParameters;
	searchFormRefresh('Account','AccountListDiv',inputParameters, tableParams, 'SearchAccounts');
}
function searchTagListRefresh(inputParameters){
	var tableParams = urlParameters;
	searchFormRefresh('Tag','TagListDiv',inputParameters, tableParams, 'SearchTags');
}
function searchContactListRefresh(inputParameters){
	var tableParams = urlParameters;
	searchFormRefresh('Contact','ContactListDiv',inputParameters, tableParams, 'SearchContacts');
}

//this method is used iin adminstration to refresh table of entitities
	// it is used in three scenario (entityClass, refreshDiv are always not-null elems)
	//1) when user click on search button. inputParameters is true
	//2) when user edit/delete/or update entity. inputParameters is null and method use to globalParameters for pager and search attributes
	//3) click on display table links. inputParameters  is not null
	function searchFormRefresh(entityClass, refreshDiv, inputParameters, globalParameters, formName){
		var parameters;
		if (inputParameters != null && (inputParameters == true || inputParameters == 'true')){
			parameters = searchFormDeserialize(entityClass,formName);
		}else {
		 	parameters = inputParameters +"&"+searchFormDeserialize(entityClass,formName);
		 	if (globalParameters != null){
				parameters += "&" + globalParameters;
			}
		}
		var url = contextPath+"/searchAction.do";
		if (formName == null) formName = "searchForm";
		var form = document.forms[formName];
		if (form != null && form.elements['shortSearch'] != null && form.elements['shortSearch'].value.length > 0){
				refreshDiv = 'quickSearchDiv';
		}
		var ajax  = submitToUpdate(url, parameters, refreshDiv);

	}
function showAdvancedOptions(mouseEvent,advContentId,advHeaderId){
	if (advContentId == null) advContentId = 'advanceSearch';
	if (advHeaderId == null) advHeaderId == 'advanceSearchHeader';
	var dimensions = Element.getDimensions($(advContentId));
	var mouseXY = getMouseXY(mouseEvent);
	var link = $('searchAdvanceLink');

	if (modalDivs.length>0){
		var modalContainer = $('modalWindow_'+modalDivs.length);
		mouseXY.x = mouseXY.x- parseFloat(modalContainer.style.left.substring(0,modalContainer.style.left.length-2));
		mouseXY.y = mouseXY.y- parseFloat(modalContainer.style.top.substring(0,modalContainer.style.top.length-2));
	}
	$(advContentId).style.top = (mouseXY.y+10) +"px";
	$(advContentId).style.left = (mouseXY.x+20) + "px";
	$(advContentId).style.width = dimensions.width +"px";
	$(advContentId).style.height = dimensions.height +"px";
	$(advContentId).style.zIndex = 90000;

	//window.centerToWindow(advContentId);
	showHide(advContentId);
	new Draggable(advContentId, {
				scroll:window,
				handle:advHeaderId
	} );
}

//deserialize Search Form. Used for filter on administration pages
	function searchFormDeserialize(entityClass, formName){
		var searchFormName = formName != null ? formName : "searchForm";
		var form = document.forms[searchFormName];
		if( form == null) {return}
		var	parameters =  Form.serialize(form);
		if (entityClass != null){
			parameters= parameters +"&entity="+entityClass;
		}
		return parameters

	}

	function lazyShowUrlInDiv(url, params, divId){
		if ($(divId).innerHTML == ""){
			submitToUpdate(url, params, divId);
		}
		$(divId).style.display='';
	}



var Util = new Object();
Util.addPx=function(number){
return number  + "px";
}

	function customRowAddEdit(formName, caseId, tableNumber, row, formToken, method, cfId){
		var params = 'method='+method+'&caseId='+caseId+"&formName="+formName+"&tableNumber="+tableNumber+'&formToken='+formToken;
		if (cfId != null) params += '&customFieldId='+cfId;
		if (row != null) params += '&rowNumber='+row;
		if (method == 'add')
			showModalDiv(contextPath+'/updateCfTable.do', params, 'xxx');

	}
var CustomTable	 = {
		init:function(formName, caseId, cfId, rowNumber, method, formToken){
			var params = 'method='+method+'&caseId='+caseId+"&formName="+formName;
			if (formToken != null) params += '&formToken='+formToken;
			if (rowNumber != null) params += '&rowNumber='+rowNumber;
			if (cfId != null) params += '&customFieldId='+cfId;
			return params;
		},
		add : function(formName, caseId, cfId, formToken){
			var params = CustomTable.init(formName, caseId, cfId, null, 'edit', formToken);
			showModalDiv(contextPath+'/updateCfTable.do', params, 'xxx');
		},
		edit: function(formName, caseId, cfId, row, formToken){
			var params = CustomTable.init(formName, caseId, cfId, row, 'edit', formToken);
			showModalDiv(contextPath+'/updateCfTable.do', params, 'xxx');
		},
		deleteRow: function(formName, caseId, cfId, row, formToken){
			CustomTable._updateForm(formName, caseId, cfId, row, formToken, 'delete', false);
		},
		update: function(formName, caseId, cfId, row, formToken, operation){
			/*var params = CustomTable.init(formName, caseId, cfId, row, 'update', formToken);
			if (!validator.validate('editCFTableRow')) {  return false;}
			var form = document.forms['editCFTableRow'];
			params += '&' + Form.serialize(form);
			params += '&operation='+operation;
			submitToUpdate(contextPath+'/updateCfTable.do', params, 'editCfTable0');
			closeModal();
			*/
			CustomTable._updateForm(formName, caseId, cfId, row, formToken, operation, true);
			//window.form.refresh();
		},
		_updateForm: function(formName, caseId, cfId, row, formToken, operation, formExist){
			if (formExist && !validator.validate('editCFTableRow')) {  return false;}
			var params = CustomTable.init(formName, caseId, cfId, row, 'update', formToken);

			if (formExist){
				var form = document.forms['editCFTableRow'];
				params += '&' + Form.serialize(form);
			}
			params += '&operation='+operation;
			submitToUpdate(contextPath+'/updateCfTable.do', params, 'editCfTable0');
			closeModal();
		}

}
	function quickAddAccount(text, value){
		addOptionInSortedSelectBox(document.forms['contactForm'].elements['accountId'],value,text,0);
	}
	function getWindowScroll(){
		var scrollX = 0
		var scrollY = 0;
		if (document.body && typeof document.body.scrollTop != "undefined") {
	        scrollX += document.body.scrollLeft;
	        scrollY += document.body.scrollTop;
	        if (document.body.parentNode &&
	            typeof document.body.parentNode.scrollTop != "undefined") {
	            scrollX += document.body.parentNode.scrollLeft;
	            scrollY += document.body.parentNode.scrollTop;
	        }
	    } else if (typeof window.pageXOffset != "undefined") {
	        scrollX += window.pageXOffset;
	        scrollY += window.pageYOffset;
	    }
		return {x: scrollX, y: scrollY};
	}
createHiddenIframe = function(id, frameName){
	iframe = document.createElement("iframe");
	iframe.id = id;
	iframe.name = frameName;
	iframe.style.borderWidth="0px";
	iframe.style.borderColor="transparent";
	iframe.frameBorder = "0";
	iframe.scrolling ="no";
	iframe.marginHeight="0";
	iframe.marginWidth="0";
	iframe.style.width="0px";
	iframe.style.height="0px";
	return iframe;
}

//for uuploading files

Uploader = {
	prepare : function(fieldId, fileName, types, size, width, height){
		Uploader.width = width;
		Uploader.height = height;
		var params = '&fieldId='+fieldId;
		if (size != null) params += "&size="+size;
		if (types != null) params += "&types="+types;
		document.domain = documentDomain;
		var iframe = $('uploadIframe');
		if (iframe == null){
			iframe = createHiddenIframe('uploadIframe','uploadIframe');
			$('uploadIframeParent').appendChild(iframe);
		}
		iframe.src = contextPath+'/uploadItem.do?method=prepare'+params+'&fieldId='+fieldId+'&fileName='+fileName;
		Uploader.show(true);
		Uploader.showWaitMessage(true);
		//modalPopUp('uploadIframeDiv', 'Upload File', true);
		//submitT('uploadIframeDiv', 'Upload File', true);
	},
	clear : function(fieldId){
		Uploader.reset(fieldId);
		$(fieldId).value = "DELETE_FILE";

	},
	reset : function(fieldId){
		var iframe = window.frames['uploadIframe'];
		if (iframe != null){
			iframe.$('fakeInput').innerHTML = '';
			hideElement(fieldId+"_image");
		}
	},
	showInfo: function(text){
		return;
		$('').innerHTML = text;
	},
	update : function(fieldId, fileName, previewLink, origFileName){
		var field = $(fieldId);
		if (field == null) {return;}
		//$(fieldId+"_info").innerHTML = origFileName;
		//Uploader.showInfo(origFileName);
		field.value = fileName;
		Uploader.show(true);
		if (previewLink != null){
			imgPreview = $(fieldId+"_image");
			if (imgPreview != null) {
				imgPreview.src = previewLink;
				imgPreview.show();

			}

		}
		//closeModal();
		if (Uploader.postFunct != null) Uploader.postFunct(fieldId, fileName, origFileName);
	},
	show : function(show){
		if (show){
			$('uploadIframe').style.width  = Uploader.width != null ? Uploader.width : "450px";
			$('uploadIframe').style.height = Uploader.height != null ? Uploader.height :  "200px";
		}else{
			$('uploadIframe').style.width = "0px";
			$('uploadIframe').style.height = "0px";
		}

	},
	showWaitMessage: function(show){
		if (show) {$('uploadDivWait').show();}
		else {
			$('uploadDivWait').hide();
		}	
	}
}
Tab = function(tabHolder, controlId,tabId, disabled) {
	if ($(controlId) == null || $(tabId) == null || tabHolder == null) {
		alert("Cannot create tab. Error: "+controlId + " or " + tabId + "  don't exists");
		return;
	}
	this.control = $(controlId);
	this.tab = $(tabId);
	this.activated = false;
	this.ajax = false;
	this.url = null;
	this.params = null;
	this.loaded = false;
	this.onActivate = null;
	this.ajaxRefresh = true;
	this.disabled = disabled != null ? disabled : false;
	var _self = this;
	this.tabHolder = tabHolder;
	this.control.onclick = function(e){
			_self.activate();
	}
	this.disable = function(){
		_self.disabled = true;
		_self.control.title = 'disabled';
		_self.control.className = 'disabled';
	}
	this.enable = function(){
		_self.disabled = false;
		_self.control.title = '';
		_self.control.className = '';
	}
	this.activate  = function(){
		if (_self.activated) return;
		if (_self.disabled ){
				return;
		}

		_self.tabHolder.deActivateAll();
		_self.activated = true;
		_self.control.className = 'active';

		if (_self.ajax){
			if ( self.ajaxRefresh || !_self.loaded){
				if (_self.ajaxFunction != null){
					_self.ajaxFunction();
				}else{
					submitToUpdate( _self.url, _self.params, _self.tab.id);
				}
				_self.loaded = true;
			}
		}
		if (_self.onActivate != null){
			_self.onActivate();
		}
		//alert('show='+_self.onActivate);
		//if (_self.onclick != null)  _self.onclick();
		showElement(_self.tab.id);

	}
	this.deActivate = function(){
		_self.activated = false;
		_self.control.className = '';
		hideElement(_self.tab.id);
		//$(_self.tab.id).style.visibility = 'hidden';
	}
	this.autoRefresh = function(state){
		_self.ajaxRefresh = state;
	}

}
Tabs = function(){

	this.tabs = new Array();
	var _self = this;
	//third parameter can be a url or function. When ajax tab in invkoed for first, there are 2 situations:
	// if url is function, then function is invoked
	// otherwise standard ajax call is created with  submitToUpdate(url, params, tabDiv) 
	this.addAjaxTab = function(controlId,tabId, url, params, disabled){
		var tab = _self.addTab(controlId, tabId, disabled);
		tab.ajax = true;
		if(typeof url == 'function') {
			tab.ajaxFunction = url;
		}else{
			tab.url = url;
			tab.params = params;
		}
		
		return tab;
	}
	this.addTab = function(controlId,tabId, disabled){
		var tab = new Tab(_self, controlId, tabId, disabled);

		this.tabs.push(tab);
		if (this.tabs.length == 1){
			tab.activate();
		}else{
			tab.deActivate();
		}
		if (tab.disabled){
			tab.disable();
		}
		return tab;

	}

	this.deActivateAll= function(){
		for(var i=0;i<_self.tabs.length;i++){
			if (! _self.tabs[i].disabled) _self.tabs[i].deActivate();
		}
	}
	this.next = function(){
		_self._activateNext(true);
	}
	this.previous = function(){
		_self._activateNext(false);
	}
	this._activateNext = function(forward){
		var activeIndex = 0;
		for(var i=0;i<_self.tabs.length;i++){
			var elem = _self.tabs[i];
			if (elem.activated) {
				activeIndex = i;
				elem.deActivate();
				break;
			};
		}
		var updated = false;
		while(!updated){
			if (forward) {
				activeIndex++;
			}else{
				activeIndex--;
			}
			activeIndex = activeIndex > -1 ? activeIndex : (_self.tabs.length-1);
			activeIndex = activeIndex < _self.tabs.length ? activeIndex : 0;
			var tab = _self.tabs[activeIndex];
			if (tab != null && !tab.disabled){
				tab.activate();
				updated = true;
			}

		}
	}
	this.back= function(controlId){
		for(var i=0;i<_self.tabs.length;i++){
			var elem = _self.tabs[i];
			if (elem.control.id == controlId)  return elem;
		}
		return null;
	}
	this.getByControl= function(controlId){
		for(var i=0;i<_self.tabs.length;i++){
			var elem = _self.tabs[i];
			if (elem.control.id == controlId)  return elem;
		}
		return null;
	}
	this.getTab= function(tabId){
		for(var i=0;i<_self.tabs.length;i++){
			var elem = _self.tabs[i];
			if (elem.tab.id == tabId)  return elem;
		}
		return null;
	}
	this.getTabByPosition= function(position){
		if (position == null || position > _self.tabs.length) return null;
		return _self.tabs[position];
	}
	this.activateTab = function(position){
		var tab = _self.getTabByPosition(position);
		if (tab != null){
			tab.activate();
		}
	}
	this.updateTabs = function(){
		for(var i=0;i<_self.tabs.length;i++){
			var elem = _self.tabs[i];
			if (!elem.disabled){
				if(elem.activated){
					elem.activate();
				}else{
					elem.deActivate();
				}
			}
		}
	}
}
WpmToggler = function(){
	this.elements = arguments;
	this.index = 0;
	var _self = this;
	this.change = function(){

		_self.index++;
		if (_self.index >= _self.elements.length){
			_self.index = 0;
		}
		for(var i=0;i< _self.elements.length;i++){
			hideElement(_self.elements[i]);
		}
		showElement( _self.elements[ _self.index] );

	}
}
//Important: Set a 'position:relative' to properties div parent
WpmElemProperties = function(id, propId){

	this.element= $(id);
	if (this.element == null) return;
	this.properties = $(propId);
	if (this.element == null || this.properties == null) return;
	var _self = this;
	this.properties.className = 'propsToggle';
	this.properties.style.display = 'none';

	this.element.observe('mouseenter', function(){
		_self.properties.show();
	});

	this.element.observe('mouseleave', function(){
		_self.properties.hide();
	});

	this.properties.parentNode.style.position = 'relative';

}
//NonAjax - Submit wpm action using form object
WpmFormSubmit = function(formName){
	synchRichTextContent();
	var validForm = validator.find(formName);
	if (validForm == null) {  return false};
	if(!validForm.validate()) return false;

	document.forms[formName].submit();
}
//Ajax - Submit wpm action using form object
WpmActionSubmitByForm = function(formName, successDiv){
	synchRichTextContent();
	if ( successDiv == null){
		successDiv 	= 'actionDiv';
	}
	submitValidateWithMethod(formName, successDiv);
}
//Ajax - Submit wpm action using formName as form identifier
WpmActionSubmit = function(formName, method, successDiv, dontDisableForm){
	synchRichTextContent();
	if ( successDiv == null){
		successDiv 	= 'actionDiv';
	}
	submitValidateFormWithMethod(formName, successDiv, method, dontDisableForm);
}
WpmPosition = {
		relativeElement : function(srcElem, pointElem, offsetX, offsetY){
		pos = findPosition(pointElem);

		if (pointElem != null){
			pointElem.style.position = 'relative';
		}
		WpmPosition._setPosition(srcElem, pos.y, pos.x, offsetX, offsetY);
	},
	toMouse : function(srcElem, offsetX, offsetY){
		WpmPosition._setPosition(srcElem, mouseXY.y, mouseXY.x, offsetX, offsetY);
	},
	_setPosition : function (srcElem, top, left, offsetX, offsetY){
		if (offsetY == null) offsetY = 0;
		if (offsetX == null) offsetX = 0;
		srcElem.style.top = (top+offsetY) +"px";
		srcElem.style.left = (left+offsetX) +"px";
		srcElem.style.display = 'block';
		srcElem.style.position = 'absolute';

	}
}
setRelativePosition = function(srcElem, relative, x, y){

}
// For NicEditor, called before Submit to synch content of RTF with TextArea
synchRichTextContent = function(){
	if(typeof nicEditors != 'undefined' && nicEditors!=null){
		for(var i=0; i < nicEditors.editors.length; i++){
			var item = nicEditors.editors[i];
			for(var j=0; j < item.nicInstances.length; j++){
				var inst = item.nicInstances[j];

				nicClearBrakeCharacters(inst);
			}
		}
	}
}
nicClearBrakeCharacters = function(inst){
	if (inst == null) return "";
	inst.saveContent();
	var textArea = inst.e;
	var regEx = new RegExp("^(<br>|<BR>)+$");
	var myMatch = regEx.exec(textArea.value);
	if(myMatch != null){
		textArea.value = textArea.value.replace(/<br>/gi,"");
	}
	return textArea.value;
}
function isIE7(){
	return (document.all && !window.opera && window.XMLHttpRequest);
}
function isIE(){
	return (document.all?true:false);
}
appendTenantParamToLink = function(){
			var allLinks = $$('a');
			var linkEl = null;
			for(var i = 0; i < allLinks.length; i++){
				linkEl = allLinks[i];
				if(linkEl.href.indexOf(wpmURL) == -1) continue;
				if(linkEl.href.indexOf('/mt/'+tnName) > -1) continue;


				if((linkEl.href.indexOf('http://') == 0 || linkEl.href.indexOf('https://') == 0) && linkEl.href.indexOf('tenantName=') <0){
					if(linkEl.href.indexOf('?')>0){
						linkEl.href = linkEl.href + '&tenantName='+tnName;
					} else {
						linkEl.href = linkEl.href + '?tenantName='+tnName;
					}
				}
			}
		};
// calculate top offset of some html element
absoluteOffset = function (elem) {
    	return elem.offsetParent && elem.offsetTop + absoluteOffset(elem.offsetParent);
}

// scroll down to some element
scrollToElement = function (id) {
	if(id == null) return;
	elem = $(id);
	if(elem == null) return;
	var offset = absoluteOffset(elem);
	if(offset < 600){
		offset = offset - 60;
	}
	window.scroll(0,offset);
}





