/*************************************************************************
(c)2004,2005 by Scalix Corporation and are the property of Scalix Corporation.
This file is available to you only under license from Scalix Corporation,
the terms of which include limited rights to install and use the software
but specifically do not permit copying and distribution of this file, and
do not permit the removal, alteration, or effacing of this notice or any
copyright or other proprietary notices contained in the software or files.
Do not use the software without a valid license from Scalix Corporation.
**************************************************************************/

// UTILITIES
gUseSoap = false;

/**
 * Sets a Cookie with the given name and value.
 *
 * name       Name of the cookie
 * value      Value of the cookie
 * [expires]  Expiration date of the cookie (default: end of current session)
 * [path]     Path where the cookie is valid (default: path of calling document)
 * [domain]   Domain where the cookie is valid
 *              (default: domain of calling document)
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */

function setCookie(name, value, expires, path, domain, secure)
{
    var cookieStr = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
    document.cookie = cookieStr;
}

/**
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
function getCookie(name)
{
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1)
    {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else
    {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

/**
 * Deletes the specified cookie.
 *
 * name      name of the cookie
 * [path]    path of the cookie (must be same as path used to create cookie)
 * [domain]  domain of the cookie (must be same as domain used to create cookie)
 */
function deleteCookie(name, path, domain)
{
    if (getCookie(name))
    {
        document.cookie = name + "=" + 
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

function determineBrowser() {
  gApp = window.navigator.appName;
  gIsNetscape = gApp == 'Netscape';
  gIsExplorer = gApp == 'Microsoft Internet Explorer';

  var testElem;

  testElem = document.createElement("DIV");
  document.body.appendChild(testElem);
  testElem.style.position = "absolute";
  testElem.style.left = 0;
  testElem.style.top = 0;
  testElem.style.width = 100;
  testElem.style.height = 20;
  testElem.style.borderLeftWidth = 10;
  testElem.style.borderLeftStyle = "solid";
  
  gInnerBorder = testElem.offsetWidth == 100;
  document.body.removeChild(testElem);

  gUnsupportedBrowser = true;

  if(typeof(getBrowser) != "undefined")
  {
    var br = getBrowser();
    var os = getOS();
    var browserID = br[0];
    var browserMajorVersion = getMajorVersion( br[1] );
    var browserMinorVersion = getMinorVersion( br[1] );
    var osID = os[0];

    if ( browserID == "msie" && osID == "win" ) {
      if ( browserMajorVersion >= 6 ||
           ( browserMajorVersion == 5 &&
             browserMinorVersion >= 5 ) ) {
        gUnsupportedBrowser = false;
      }
    } else if ( browserID == "mozsea" ) {
      if ( browserMajorVersion > 1 ||
           ( browserMajorVersion == 1 &&
             browserMinorVersion >= 7 ) ) {
        gUnsupportedBrowser = false;
      }
    } else if ( browserID == "firefox" ) {
      if ( browserMajorVersion >= 1 |
           ( browserMajorVersion == 0 &&
             browserMinorVersion >= 10 ) ) {
        gUnsupportedBrowser = false;
      }
    }
  }
}

function getGlobalValues(opener, initFunc) {
  if (opener != null && opener.baseAdminWindow != null) {
    gApp = opener.navigator.appName;
    gIsNetscape = opener.gIsNetscape;
    gIsExplorer = opener.gIsExplorer;
    gInnerBorder = opener.gInnerBorder;
    baseAdminWindow = opener.baseAdminWindow;
    callingDialogObj = opener.dialogObj;
    callingWindowObj = opener.windowObj;
    globalInitFunc = opener.globalInitFunc;
    CountryInfoCode2 = opener.CountryInfoCode2;
    StateProvinceByCountry = opener.StateProvinceByCountry;
    LanguageCountryArray = opener.LanguageCountryArray;
    LanguageInfoArray = opener.LanguageInfoArray;
    adminApp = opener.adminApp;
    gDebug = opener.gDebug;
    gUseSoap = opener.gUseSoap;
    isFile = opener.isFile;
    baseUrl = opener.baseUrl;
    testingXML = opener.testingXML;
    displayXML = opener.displayXML;
    adminInfo = opener.adminInfo;
    settingsArray = opener.settingsArray;
    LocalConfig = opener.LocalConfig;
    opener.globalInitFunc(window);
    GlobalData = opener.GlobalData;
  } else {
    determineBrowser();
    baseAdminWindow = window;
    globalInitFunc = initFunc;
  }
}

function getTestValues(opener) {
  //UserInfo.testArray = opener.UserInfo.testArray;
  //GroupInfo.testArray = opener.GroupInfo.testArray;
}


callStack = new Array();
callStackPos = 0;

function pushFunc(funcName) {
  callStack[callStackPos] = funcName;
  callStackPos = callStackPos + 1;
}

function popFunc() {
  callStackPos = callStackPos - 1;
}

function getCallStack() {
  var str = "";
  for (i = callStackPos - 1; i >= 0; i--) {
    str = str + callStack[i] + "\n";
  }
  return str;
}

function setWindowDimensions() {
  pushFunc("setWindowDimensions");

  if(window.innerWidth) {
    gWindowHeight = window.innerHeight;
    gWindowWidth = window.innerWidth;
  } else {
    gWindowHeight = document.body.parentElement.scrollHeight;
    gWindowWidth = document.body.parentElement.scrollWidth;
  }

  if (gWindowWidth < gMinWidth) {
    gWindowWidth = gMinWidth;
  }

  if (gWindowHeight < gMinHeight) {
    gWindowHeight = gMinHeight;
  }

  popFunc();
}

function resizeWindow() {
  pushFunc("resizeWindow");

  var gui = this.GUI;
  gui.relayout();


  popFunc();
}

function getStyleValueFromElement(elem, styleName) {
  if (elem.currentStyle != null) {
    return elem.currentStyle[styleName];
  }

  var myStyle = window.getComputedStyle(elem, "");
  return myStyle.getPropertyValue(styleName);
}

function getWindowPosition(elem) {
    var x = 0;
    var y = 0;
    while (elem != null && elem.offsetLeft != null) {
        x = x + elem.offsetLeft;
        y = y + elem.offsetTop;
        elem = elem.parentNode;
    }
    var o = new Object;
    o.left = x;
    o.top = y;
    return o;
}

function setBorder(elem, style, color, width) {
  elem.style.borderBottomColor = color;
  elem.style.borderBottomStyle = style;
  elem.style.borderBottomWidth = width;
  elem.style.borderTopColor = color;
  elem.style.borderTopStyle = style;
  elem.style.borderTopWidth = width;
  elem.style.borderLeftColor = color;
  elem.style.borderLeftStyle = style;
  elem.style.borderLeftWidth = width;
  elem.style.borderRightColor = color;
  elem.style.borderRightStyle = style;
  elem.style.borderRightWidth = width;
}

//**********************************************************************
//  BEGIN MODAL DIALOG CODE (can also be loaded as external .js file)
//***********************************************************************/

// Global for brower version branching.

// One object tracks the current modal dialog opened from this window.

var dialogObj = new Object();
windowObj = new Object();
handledClosedWindowTimestamp = 0;
closedWindowTimestamp = 0;
closeWindowTimeout = null;
openedWindows = new Array();
windowIndex = 0;

function openWindow(baseURL, width, height, args, returnFunc, returnObj)
{
  windowObj.url = baseURL + ((isFile) ? ".html" : ".jsp");
  windowObj.args = args;
  windowObj.width = width;
  windowObj.height = height;

  windowObj.name = window.name + "_" + windowIndex++;

  var attr = "left=" + 0 + ", top=" + 0 + ", width=" + width + ", height=" + height + ", status=no, resizable=yes";

  windowObj.win = window.open(windowObj.url, windowObj.name, attr);

  var len = openedWindows.length;
  for (var i = 0; i < len; i++) {
    if (openedWindows[i] == null) {
      break;
    }
  }
  var obj = new Object();
  obj.win = windowObj.win;
  obj.returnFunc = returnFunc;
  obj.returnObj = returnObj;
  openedWindows[i] = obj;

  if (closeWindowTimeout == null) {
    closeWindowTimeout = setTimeout("callWindowCloseFunc()", 50);
  }

  return windowObj.win;
};

function callWindowCloseFunc() {
  var tempTimestamp = closedWindowTimestamp;
  if (handledClosedWindowTimestamp < closedWindowTimestamp) {
    var len = openedWindows.length;
    for (var i = 0; i < len; i++) {
      var obj  = openedWindows[i];
      if (obj != null && obj.win != null && obj.win.closed) {
	openedWindows[i] = null;
	if (obj.returnFunc != null) {
	  obj.returnFunc(obj.returnObj);
	}
      }
    }
    handledClosedWindowTimestamp = tempTimestamp;
  }
  closeWindowTimeout = setTimeout("callWindowCloseFunc()", 50);
}

function openModalDialog(baseURL, width, height, returnFunc, returnObj, args, extraAttr) {
  var url = baseURL + ((isFile) ? ".html" : ".jsp");

  try
  {
    openDGDialog(url, width, height, returnFunc, returnObj, args, extraAttr);
  }
  catch(ex)
  {
    window.alert(UIstrings.PopupsBlocked);
  }
}

// Generate a modal dialog.
// Parameters:
//    url -- URL of the page/frameset to be loaded into dialog
//    width -- pixel width of the dialog window
//    height -- pixel height of the dialog window
//    returnFunc -- reference to the function (on this page)
//                  that is to act on the data returned from the dialog
//    returnObj - object that is expected to be returned as the parameter to returnFunc
//    args -- [optional] any data you need to pass to the dialog

function openDGDialog(url, width, height, returnFunc, returnObj, args, extraAttr)
{
  if(!dialogObj.win || (dialogObj.win && dialogObj.win.closed))
  {
    // Initialize properties of the modal dialog object.
    dialogObj.returnFunc = returnFunc;
    dialogObj.returnObj = returnObj;
    dialogObj.returnedValue = "";
    dialogObj.args = args;
    dialogObj.url = url;
    dialogObj.width = width;
    dialogObj.height = height;
    // Keep name unique so Navigator doesn't overwrite an existing dialog.
    dialogObj.name = window.name + "_" + windowIndex++;
    // Assemble window attributes and try to center the dialog.

	// Firefox 3 has implemented the showModalDialog method but it is
	// incomplete and buggy. We need to check the platform for now. 
	var browser = getBrowser();
    if(window.showModalDialog != null && browser[2] == "msie")
    {
      window.showModalDialog(
	  	url,
		window ,
	  	"dialogHeight: " + height + "px; dialogWidth: " + width +
			"px; center: Yes; help: No; resizable: No; status: No;");
    }
	else
	{
	  if(window.screenX != null && window.outerWidth != null)
	  {
		  // gNetscape?
		  // Center on the main window.
		  dialogObj.left = window.screenX + 
			  ((window.outerWidth - dialogObj.width) / 2);
		  dialogObj.top = window.screenY + 
			  ((window.outerHeight - dialogObj.height) / 2);
		  var attr = "screenX=" + dialogObj.left + 
			  ",screenY=" + dialogObj.top + ",resizable=no,width=" + 
			  dialogObj.width + ",height=" + dialogObj.height;
	  }
	  else
	  {
		  // The best we can do is center in screen.
		  dialogObj.left = (screen.width - dialogObj.width) / 2;
		  dialogObj.top = (screen.height - dialogObj.height) / 2;
		  var attr = "left=" + dialogObj.left + ",top=" + 
			  dialogObj.top + ",resizable=no,width=" + dialogObj.width + 
			  ",height=" + dialogObj.height;
	  }

    if (extraAttr != null)
      attr = attr + "," + extraAttr;

	  // Generate the dialog and make sure it has focus.
	  dialogObj.win=window.open(dialogObj.url, dialogObj.name, attr);
	  dialogObj.win.onbeforeunload = HandleOnBeforeUnload;
	  dialogObj.win.focus();
	}

    setTimeout("callReturnFunc()", 50);
  }
  else
  {
    dialogObj.win.focus();
  }
}

function HandleOnBeforeUnload()
{
  closeSubWindows(dialogObj.win);
};

function closeSubWindows(win)
{
  if(win != null)
  {
    if(win.dialogObj != null)
      closeSubWindows(win.dialogObj.win);

    win.close();
  }
};

// Event handler to inhibit Navigator form element 
// and IE link activity when dialog window is active.
function deadend(e) {
  var evt = (e == null) ? window.event : e;

  if (dialogObj.win && !dialogObj.win.closed) {
    window.status = "In Deadend";
    dialogObj.win.focus();
    if (evt.preventDefault != null) {
      evt.preventDefault();
    }
    if (evt.stopPropagation != null) {
      evt.stopPropagation();
    } else {
      evt.cancelBubble = true;
    }

    evt.returnValue = false;
    return false;
  }
}

startFrame = 1;

// Since links in IE4 cannot be disabled, preserve 
// IE link onclick event handlers while they're "disabled."
// Restore when re-enabling the main window.
var IELinkClicks

// Disable form elements and links in all frames for IE.
function disableForms() {
	IELinkClicks = new Array()
	for (var h = startFrame; h < frames.length; h++) {
		for (var i = 0; i < frames[h].document.forms.length; i++) {
			for (var j = 0; j < frames[h].document.forms[i].elements.length; j++) {
				frames[h].document.forms[i].elements[j].disabled = true
			}
		}
		IELinkClicks[h] = new Array()
		for (i = 0; i < frames[h].document.links.length; i++) {
			IELinkClicks[h][i] = frames[h].document.links[i].onclick
			frames[h].document.links[i].onclick = deadend
		}
		frames[h].window.onfocus = checkModal
    	frames[h].document.onclick = checkModal
	}
}

// Restore IE form elements and links to normal behavior.
function enableForms() {
	for (var h = startFrame; h < frames.length; h++) {
		for (var i = 0; i < frames[h].document.forms.length; i++) {
			for (var j = 0; j < frames[h].document.forms[i].elements.length; j++) {
				frames[h].document.forms[i].elements[j].disabled = false
			}
		}
		for (i = 0; i < frames[h].document.links.length; i++) {
			frames[h].document.links[i].onclick = IELinkClicks[h][i]
		}
	}
}

// Grab all Navigator events that might get through to form
// elements while dialog is open. For IE, disable form elements.
function blockEvents() {
  if (document.addEventListener != null) {
    document.addEventListener("mouseup", deadend, true);
    document.addEventListener("mousedown", deadend, true);
    document.addEventListener("mouseover", deadend, true);
    document.addEventListener("click", deadend, true);
    document.addEventListener("focus", deadend, true);
  } else {
    if (window.captureEvents) {
      window.captureEvents(Event.CLICK | Event.MOUSEDOWN | Event.MOUSEUP | Event.FOCUS);
      window.onclick = deadend;
      window.onmousedown = deadend;
      window.onmouseup = deadend;
      window.onfocus = deadend;
    } else {
      disableForms();
    }
  }
  window.onfocus = checkModal
}
// As dialog closes, restore the main window's original
// event mechanisms.
function unblockEvents() {
  if (document.removeEventListener != null) {
    document.removeEventListener("mousemove", deadend, true);
    document.removeEventListener("mouseup", deadend, true);
    document.removeEventListener("mousedown", deadend, true);
    document.removeEventListener("click", deadend, true);
    document.removeEventListener("focus", deadend, true);
  } else {
    if (window.releaseEvents) {
      window.releaseEvents(Event.CLICK | Event.MOUSEDOWN | Event.MOUSEUP | Event.FOCUS )
	window.onclick = null;
      window.onmousedown = null;
      window.onmouseup = null;
      window.onfocus = null;
      window.onmouseover = null;
      window.onmouseout = null;
    } else {
      enableForms();
    }
  }
}

// Invoked by onFocus event handler of EVERY frame,
// return focus to dialog window if it's open.
function checkModal() {
	setTimeout("finishChecking()", 50)
	return true
}

function finishChecking() {
	if (dialogObj.win && !dialogObj.win.closed) {
		dialogObj.win.focus() 
	}
}

function callReturnFunc() {
  if (dialogObj.win && ! (dialogObj.win.closed || dialogObj.win.toBeClosed)) {
    setTimeout("callReturnFunc()", 50);
  } else {
    if (dialogObj.win && ! dialogObj.win.closed) {
      dialogObj.win.close();
    }
    if (dialogObj.returnFunc) {
      dialogObj.returnFunc(dialogObj.returnObj, dialogObj.returnedValue);
    }
    unblockEvents();
  }
}

//**************************
//  END MODAL DIALOG CODE
//**************************/

function quoteLDAPstring(str) {
  var len = str.length;
  var newStr = null;
  var start = len;

  for (var i = 0; i < len; i++) {
    var c = str.charAt(i);
    if (c == '(' || c == ')') {
      if (newStr == null) {
	newStr = str.substring(0, i);
      } else if (i > start) {
	newStr += str.substring(start, i);
      }
      start = len;
      if (nc == '(') {
	newStr += "\\28";
      } else {
	newStr += "\\29";
      }
    } else if (c == '\\') {
      // quoted character in the search string
      if (i < len - 1) {
	// there is another character, otherwise igore the slash
	var nc = str.charAt(i + 1);
	if (newStr == null) {
	  newStr = str.substring(0, i);
	} else if (i > start) {
	  newStr += str.substring(start, i);
	}
	start = len;
	if (nc == '*') {
	  newStr += "\\2a";
	  i++;
	} else if (nc == '\\') {
	  newStr += "\\5c";
	  i++;
	}
      } else {
	if (newStr == null) {
	  newStr = str + "\\5c";
	} else if (i > start && start != -1) {
	  newStr += str.substring(start, i) + "\\5c";
	}
	start = len;
      }
    } else {
      if (start == len) {
	start = i;
      }
    }
  }

  if (newStr == null) {
    return str;
  } else if (start != len) {
    return newStr + str.substring(start, len);
  } else {
    return newStr;
  }
}


function quoteRegExpString(str, allowWhiteSpace) {
  var len = str.length;
  var newStr = null;
  var start = len;

  for (var i = 0; i < len; i++) {
    var c = str.charAt(i);
    if (c == '(' || c == ')' || c == '[' || c == ']' || c == '^' || c == '$' || c == '.' || c == '+' || c == '?') {
      if (newStr == null) {
	newStr = str.substring(0, i) + '\\' + c;
      } else if (i > start) {
	newStr += str.substring(start, i) + '\\' + c;
      }
      start = len;
    } else if (c == '*') {
      if (newStr == null) {
	newStr = str.substring(0, i) + ((allowWhiteSpace) ? '.*' : '\\S*');
      } else if (i > start) {
	newStr += str.substring(start, i) + ((allowWhiteSpace) ? '.*' : '\\S*');
      }
      start = len;
    } else  if (c == '\\') {
      // quoted character in the search string
      if (i < len - 1) {
	// there is another character, otherwise igore the slash
	var nc = str.charAt(i + 1);
	if (newStr == null) {
	  newStr = str.substring(0, i);
	} else if (i > start) {
	  newStr += str.substring(start, i);
	}
	start = len;
	if (nc == '*') {
	  newStr += "\\*";
	  i++;
	} else if (nc == '\\') {
	  newStr += "\\\\";
	  i++;
	}
      } else {
	if (newStr == null) {
	  newStr = str + "\\" ;
	} else if (i > start && start != -1) {
	  newStr += str.substring(start, i + 1) + "\\";
	}
	start = len;
      }
	
    } else {
      if (start == len) {
	start = i;
      }
    }
  }

  if (newStr == null) {
    return str;
  } else if (start != len) {
    return newStr + str.substring(start, len);
  } else {
    return newStr;
  }
}

function getErrorString(xmlTree, defaultStr) {
  if (xmlTree != null) {
    var errorCodeElems = xmlTree.getElementsByTagName("errorcode");
    if (errorCodeElems != null && errorCodeElems.length != 0) {
      var errorCode = errorCodeElems[0].firstChild.data;

      if (UIstrings.errors[errorCode] != null) {
	return UIstrings.errors[errorCode];
      }
    }
  }
  return defaultStr;
}

function copyArray(arr1)
{
  var arr2 = new Array();

  for(var i in arr1)
  {
    arr2[i] = arr1[i];
  }

  return arr2;
};

function matchParens(expr)
{
  var count = 0;

  if(expr == null)
    return true;

  for(var i = 0;i < expr.length;i++)
  {
    if(expr[i] == '(')
      count++;
    if(expr[i] == ')')
      count--;

    if(count < 0)
      return false;
  }

  return (count == 0);
};

function decimalToString(num)
{
  var str = num.toString();

  str = str.replace(/\./g, UIstrings.Decimal);

  return str;
};

function KBtoHumanReadable(val, includeString, fractionalDigits, omitSpace)
{
  var retVal = "";

  if(fractionalDigits == null)
    fractionalDigits = 3;

  var power = Math.pow(10, fractionalDigits);

  var KBperGB = LocalConfig.KBperMB * LocalConfig.KBperMB;

  if(val < LocalConfig.KBperMB)
  {
    val = Math.round(val * power) / power;
    retVal = decimalToString(val) + ((includeString) ? UIstrings.KBLabel : "");
  }
  else if(val < KBperGB)
  {
    val = val / LocalConfig.KBperMB;
    val = Math.round(val * power) / power;
    retVal = decimalToString(val) + ((includeString) ? UIstrings.MBLabel : "");
  }
  else
  {
    val = val / KBperGB;
    val = Math.round(val * power) / power;
    retVal = decimalToString(val) + ((includeString) ? UIstrings.GBLabel : "");
  }

  if(omitSpace)
  {
    retVal = retVal.replace(" ","");
  }

  return retVal;
};
