// =============================================================================
// Library of functions used in DS Administration
//
// $Id: admin.js 446 2008-10-07 11:09:51Z kwb $

// -----------------------------------------------------------------------------
// trim the spaces enclosed the core of text
// -----------------------------------------------------------------------------

function trim(value) {
	if (!value || (value == null) || (value.length == 0)) {
		return "";
  }

	var i = 0, startPos = 0, endPos = 0;
	while (i < value.length) {
		if (value.charAt(i) != ' ') {
			break;
		}
		i++;
	}
	if (i == value.length) {
		return "";
	}
	startPos = i;

	i = value.length - 1;
	while (i > 0) {
		if (value.charAt(i) != ' ') {
			endPos = i;
			break;
		}
		--i;
	}
	if (endPos == 0) {
		endPos = startPos;
	}
	return value.substring(startPos, endPos + 1);
}

// -----------------------------------------------------------------------------
// trim the spaces on right side enclosed the core of text
// -----------------------------------------------------------------------------

function rtrim(value) {
  var result = value;
  while('' + result.charAt(result.length - 1) == ' ') {
    result = result.substring(0, result.length - 1);
  }
  return result;
}

// -----------------------------------------------------------------------------
// Check if the given string is blank (empty after trim)
// -----------------------------------------------------------------------------
function isBlank(str) {
  for (i = 0; i < str.length; i++) {
    if (str.charAt(i) != ' ') {
      return false;
    }
  }
  return true;		  
}

// -----------------------------------------------------------------------------
// Replace substring in string with another substring
// sourceString .. source text
// oldString    .. substring to be replaced
// newString    .. substring to be used as a replacement
// replaceAll   .. flag if replace all (true) or only first (false) occurence of oldString
// -----------------------------------------------------------------------------

function strReplace(sourceString, oldString, newString, replaceAll) {
  // check inputs
  if (!sourceString) sourceString = "";
  if (!oldString) oldString = "";
  if (!newString) newString = "";
  if (!replaceAll) replaceAll = false;

  // check next action
	if ((sourceString == null) || (sourceString.length == 0)) {
		return "";
	}
	if ((oldString == null) || (oldString.length == 0)) {
		return sourceString;
	}
	if (newString == null) {
		newString = "";
	}

	var indexOld = 0;
	var indexNew = sourceString.indexOf(oldString, indexOld);
	if (indexNew < 0) {
		return sourceString;
	}

	var lengthOld = oldString.length;
	var sbTemp = "";
	while (indexNew >= 0) {
		sbTemp += sourceString.substring(indexOld, indexNew) + newString;
		indexOld = indexNew + lengthOld;
		if (!replaceAll) {
			break;
		}
		indexNew = sourceString.indexOf(oldString, indexOld);
	}
	sbTemp += sourceString.substring(indexOld);

	return sbTemp;
}
// -----------------------------------------------------------------------------
// close popup / modal window
// -----------------------------------------------------------------------------
function closePopupOrGreybox(){
  /*if((top.window.GB_open)&&(top.window.GB_windows.lenght>0)){*/
  /*if((top.window.GB_open)||(window.GB_open)){*/
  if ((top) && (top.window) && (top.window.GB_windows) && (top.window.GB_windows.length >= 1)) {
    top.window.GB_close();
  }else{
    self.close();
  }
}


// -----------------------------------------------------------------------------
// Get selected value from the given combobox or default value if nothing is selected
// -----------------------------------------------------------------------------
function getComboValue(combo, defaultValue) {
  return (combo.selectedIndex >= 0) ? combo[combo.selectedIndex].value : defaultValue;
}

// -----------------------------------------------------------------------------
// Set the given value to the given combobox, do nothing is no selection in combo is active
// -----------------------------------------------------------------------------
function setComboValue(combo, value) {
  if (combo.selectedIndex >= 0) {
    combo[combo.selectedIndex].value = value;
  }
}

// -----------------------------------------------------------------------------
// Return value of given parameter from passed URL.
// -----------------------------------------------------------------------------

function getUrlParamValue(_url, _paramName) {
	var url = new String(_url);
	var paramName = new String(_paramName);

	// alert("getUrlParamValue(" + url + ", " + paramName + ")");
	if ((url == null) || (paramName == null) || (paramName.length == 0)) {
		return "";
	}
	// find parameter in URL
	var indexStart = url.indexOf(paramName + "=");
	if (indexStart < 0) {
		return "";
	}
	indexStart += paramName.length + 1;       // "="
	var indexEnd = url.indexOf("&", indexStart + 1);
	if (indexEnd < 0) {
		indexEnd = url.length;
	}

	// get parameter value
	return url.substring(indexStart, indexEnd);
}

// -----------------------------------------------------------------------------
// Check if value is numberic. realEnabled=true means that real numbers are enabled
// -----------------------------------------------------------------------------
function isNumeric(sText, realEnabled) {
	sText = trim(sText);
	if (sText == "") {
		return false;
	}

	var validChars = "0123456789", isNumber = true, digit;
	if (realEnabled) {
		validChars += "."
	}

  var foundFraction = false;  
	for (i = 0; i < sText.length && isNumber == true; i++) {
		digit = sText.charAt(i);
		if (validChars.indexOf(digit) == -1) {
			isNumber = false;
		} else if (digit == '.') {
      if (foundFraction) {
        isNumber = false;
      } else {
        foundFraction = true;
      }
    }
	}

	return isNumber;
}

// -----------------------------------------------------------------------------------
// Check if value is numeric and in range borders inclusive.
// realEnabled=true means that real numbers are enabled
// -----------------------------------------------------------------------------------

function isNumericInRange(sText, realEnabled, signEnabled, minValue, maxValue) {
	var value = parseInt(sText, 10);
	return !isNaN(value) && isNumeric(sText, realEnabled, signEnabled) && (value >= minValue) && (value <= maxValue);
};

// -----------------------------------------------------------------------------
// Check if given string contains german umlauts.
// Returns true if yes, otherwise false.
// -----------------------------------------------------------------------------

var umlauts = "öäüÖÄÜß";

function containsUmlauts(str) {
	var i;
	var ch;
	for (i = 0; i < str.length; i++) {
		ch = str.charAt(i);
		if (umlauts.indexOf(ch) >= 0) {
			return true;
		}
	}

	return false;
}

// -----------------------------------------------------------------------------
// Simple encoding of a specified string.
// Any "/" character will be replaced by "%2F". This can be used for avoiding slashes
// in request parameters since some servlet environments have problems with such URLs.
// -----------------------------------------------------------------------------

function simpleEscape(str) {
    return str.replace(/\//g, "%2F");
}

// -----------------------------------------------------------------------------
// Escape apostrofs in specified string with \'
// -----------------------------------------------------------------------------
function escapeApos(str) {
  if (isBlank(str)) {
	  return str;
	}
  return str.replace(/'/g, "\\'");
}

// -----------------------------------------------------------------------------
// Prepare string for HTML alt attribute
// -----------------------------------------------------------------------------

function toHtmlAlt(str) {
	str = strReplace(str, '"', "&#39;", true);
  str = strReplace(str, "'", "&#39;", true);
  str = strReplace(str, ">", "&gt;", true);
  str = strReplace(str, "<", "&lt;", true);
  return str;
}

// -----------------------------------------------------------------------------
// Escape the characters in a String using HTML entities 
// NOTE: it uses numeric entities only
// See org.apache.commons.lang.StringEscapeUtils.escapeHtml()
// -----------------------------------------------------------------------------

function escapeHtml(str) {
  if (!str || isBlank(str)) {
    return str;
  }
  var results = [];
  for (i = 0; i < str.length; i++) {
    var code = str.charCodeAt(i);
    if (code > 127) {
      results.push("&#" + String(code) + ";");
    } else {
      results.push(str.charAt(i));
    }
  }
  return results.join('');
}

// -----------------------------------------------------------------------------
// Return folder parsed from fileURL.
// Example:
//   /pages/index.html -> /pages/
//   index.html -> empty string
// -----------------------------------------------------------------------------

function extractFolder(filePath) {
  if (!filePath) {
    return "";
  }
	var pos = filePath.lastIndexOf("/");
	if (pos < 0) {
		return "";
	}
	return filePath.substring(0, pos + 1);
};

/*
 * Delete only if clicked "yes"
 *
 */
function deleteAssetfromImagegallery(globalAssetId){
  var text = "Möchten Sie die Datei wirklich löschen?\nDrücken Sie OK zum löschen oder brechen Sie mit Abbrechen ab!"
  if(confirm(text)){
    doListAction(window.document.form_am, 'f_action', 'delete', 'f_asset_id', globalAssetId);
  }
  return;
}

// -----------------------------------------------------------------------------
// Open AssetManagement window as popup.
// @param sysPagesFolder DS pages folder start and finished with delimiter "/"
// @param imageId string representing image ID
// -----------------------------------------------------------------------------
var ASSET_TYPE_IMAGE  = "image"; // Image file
var ASSET_TYPE_LINK   = "link";  // Link content (set of the files with the same sense)
var ASSET_TYPE_TEXT   = "text";  // Text content created by author
var ASSET_TYPE_HTML   = "html";  // HTML code content
var ASSET_TYPE_FILE   = "file";  // Download file
var ASSET_TYPE_MEDIA  = "media"; // Media file (used for podcast)
var url = "";
var width = "";
var height = "";
var winId = "";

function callAm(sysPagesFolder, assetType, assetId, callbackId) {
	var pageUrl, win, viewParams, initParams, winName, leftPosition, winHeight;
  if (assetType == ASSET_TYPE_IMAGE) {
    pageUrl = "am.html";
  } else if (assetType == ASSET_TYPE_FILE) {
    pageUrl = "am_files.html";
  } else if (assetType == ASSET_TYPE_MEDIA) {
    pageUrl = "am_media.html";
  } else {
    return;
  }
	initParams = 'f_opener_type=admin&f_asset_type=' + assetType;
	viewParams = ( ((trim(assetId) != "") && (eval(assetId) > 0)) ? "&f_action=edit&f_asset_id=" + assetId : "&f_action=list" );
	viewParams += ( (trim(callbackId) != "") ? "&f_callback_id=" + trim(callbackId) : "");
	winName = 'am_admin';
	leftPosition = screen.width - 549;
	winHeight = ( (screen.width > 800) ? 700 : 500 );
	
  if (top.window.GB_open || window.GB_open) {
    if (assetType == ASSET_TYPE_IMAGE) {
      winId = "ASSET_TYPE_IMAGE";
    } else if (assetType == ASSET_TYPE_FILE) {
      winId = "ASSET_TYPE_FILE";
    } else if (assetType == ASSET_TYPE_MEDIA) {
      winId = "ASSET_TYPE_MEDIA";
    }
    url = sysPagesFolder + pageUrl + "?" + initParams + viewParams, winName;
    width = 810;/*542*/;
    height = 600;
    top.window.setTimeout("top.window.GB_open(url,winId,width,height,'')", 500);
  } 
  else { 
	  win = window.open(sysPagesFolder + pageUrl + "?" + initParams + viewParams, winName,
		  "width=810, height=" + winHeight + ", top=5, left=" + leftPosition + ", scrollbars=yes, menubar=no");
    if (win != null) {
  	  win.opener = self;
    	win.focus();
    }
  }
};

// -----------------------------------------------------------------------------
// Open popup window with directory tree and expand fileURL folder
// @param rootPath Root path - MySite home folder or "/"
// @param fileURL name of focused folder
// -----------------------------------------------------------------------------

var directoryWindow = null;
var directoryOpenerWindow = null;
var directoryFormName = null;
var directoryFieldName = null;

function setFormValue(filename) {
  if ((directoryFormName != null) && (directoryFieldName != null)) {
    var field;
    if (directoryOpenerWindow != null) {
      field = directoryOpenerWindow.document.forms[directoryFormName].elements[directoryFieldName];
    } else {
      field = document.forms[directoryFormName].elements[directoryFieldName];
    }
    if (field) {
      field.value = filename;
    }
  }
  if (directoryWindow != null) {
    directoryWindow.close();
    directoryWindow = null;
  }
  if (window.onResourceSelectedInTree) {
    onResourceSelectedInTree(filename);  
  }
}

// deprecated - should be replaced by callSelectResourceOld() or callSelectResource()

function callDirectoryWindowForMysite(servletPath, rootPath, fileURL, formName, formFieldName, showfiles) {
  directoryFormName = formName;
  directoryFieldName = formFieldName;
  var focusedFolder = extractFolder(fileURL);
	directoryWindow = window.open(servletPath + "/system/workplace/jsp/tree_fs.html?resource=" + simpleEscape(focusedFolder)
		+ "&lastknown=" + rootPath + (showfiles ? "&includefiles=true" : ""), "folder_tree",
		"toolbar=no,location=no,directories=no,status=no,menubar=0,scrollbars=yes,resizable=yes,top=10,left=10,width=300,height=500");
	if (directoryWindow != null) {
		if (directoryWindow.opener == null) {
			directoryWindow.opener = self;
		}
		directoryWindow.focus();
	} 
};

// open resources tree limited by admin mysite path
var SELECTABLE_TYPE_FOLDER = "folder";
var SELECTABLE_TYPE_FILE   = "file";
function callDirectoryWindow(fileURL, formName, formFieldName, showfiles, selectableTypes) {
  if(fileURL.indexOf("http://") == 0){
    callDirectoryWindowEx(" ", formName, formFieldName, showfiles, selectableTypes, self);
  } else {
    callDirectoryWindowEx(fileURL, formName, formFieldName, showfiles, selectableTypes, self);
  }
}
function callDirectoryWindowEx(fileURL, formName, formFieldName, showfiles, selectableTypes, self){
  directoryFormName = formName;
  directoryFieldName = formFieldName;
  directoryOpenerWindow = opener;
  var params = "?f_init=1", focusedFolder = extractFolder(fileURL);
  if (focusedFolder != "") {
    params += "&f_resource_path=" + focusedFolder;
  }
  if (showfiles) {
    params += "&f_includefiles=true";
  }
  if (selectableTypes && selectableTypes.length) {
    params += "&f_selectable_type=";
    for (var i = 0; i < selectableTypes.length; i++) {
      params += (i > 0 ? "," : "") + trim(selectableTypes[i]);
    }
  }
  if (top.window.GB_open) {
      var url = context.sp + context.dspagesfolder + "tree_popup.html" + params;
      var winId = "folder_tree";
      var width = 300;
      var height = 500;
      top.window.GB_open(url,winId,width,height,'');
  } 
  else { 
  	directoryWindow = window.open(context.sp + context.dspagesfolder + "tree_popup.html" + params, "folder_tree",
  		"toolbar=no,location=no,directories=no,status=no,menubar=0,scrollbars=yes,resizable=yes,top=10,left=10,width=300,height=500");
  	if (directoryWindow != null) {
  		if (directoryWindow.opener == null) {
  			directoryWindow.opener = opener;
  		}
  		directoryWindow.focus();
  	}
  }
}


function callSelectResource(fileURL, formName, formFieldName, showfiles, selectableTypes) {
  callSelectResourceEx(fileURL, formName, formFieldName, showfiles, selectableTypes, self);
}

function callSelectResourceEx(fileURL, formName, formFieldName, showfiles, selectableTypes, opener) {
  directoryFormName = formName;
  directoryFieldName = formFieldName;
  directoryOpenerWindow = opener;
  var params = "?f_init=1", focusedFolder = extractFolder(fileURL);
  if (focusedFolder != "") {
    params += "&f_resource_path=" + focusedFolder;
  }
  if (showfiles) {
    params += "&f_includefiles=true";
  }
  if (selectableTypes && selectableTypes.length) {
    params += "&f_selectable_type=";
    for (var i = 0; i < selectableTypes.length; i++) {
      params += (i > 0 ? "," : "") + trim(selectableTypes[i]);
    }
  }
  if (top.window.GB_open) {
      //var url = context.sp + context.dspagesfolder + "explorer/tree_popup.html" + params;
      var url = context.sp + context.dspagesfolder + "tree_popup.html" + params;
      var winId = "folder_tree";
      var width = 300;
      var height = 500;
      top.window.GB_open(url,winId,width,height,'');
  } 
  else { 
  	directoryWindow = window.open(context.sp + context.dspagesfolder + "explorer/tree_popup.html" + params, "folder_tree",
  		"toolbar=no,location=no,directories=no,status=no,menubar=0,scrollbars=yes,resizable=yes,top=10,left=10,width=300,height=500");
  	if (directoryWindow != null) {
  		if (directoryWindow.opener == null) {
  			directoryWindow.opener = opener;
  		}
  		directoryWindow.focus();
  	}
  }
}
function callSelectResourceForTinyMce(fileURL, formName, formFieldName, showfiles, selectableTypes) {
  callSelectResourceForTinyMceEx(fileURL, formName, formFieldName, showfiles, selectableTypes, self);
}

function callSelectResourceForTinyMceEx(fileURL, formName, formFieldName, showfiles, selectableTypes, opener) {
  directoryFormName = formName;
  directoryFieldName = formFieldName;
  directoryOpenerWindow = opener;
  var params = "?f_init=1", focusedFolder = extractFolder(fileURL);
  if (focusedFolder != "") {
    params += "&f_resource_path=" + focusedFolder;
  }
  if (showfiles) {
    params += "&f_includefiles=true";
  }
  if (selectableTypes && selectableTypes.length) {
    params += "&f_selectable_type=";
    for (var i = 0; i < selectableTypes.length; i++) {
      params += (i > 0 ? "," : "") + trim(selectableTypes[i]);
    }
  }
  directoryWindow = window.open(context.sp + context.dspagesfolder + "explorer/tree_popup.html" + params, "folder_tree",
    "toolbar=no,location=no,directories=no,status=no,menubar=0,scrollbars=yes,resizable=yes,top=10,left=10,width=300,height=500");
  if (directoryWindow != null) {
    if (directoryWindow.opener == null) {
      directoryWindow.opener = opener;
    }
  directoryWindow.focus();
  }
}

// close resource selection popup if it's still opened
function closeSelectResourcePopup() {
  if (directoryWindow != null) {
    if (top.window.GB_close){
      directoryWindow.GB_close();
      directoryWindow = null;
    }
    else{
      directoryWindow.close();
      directoryWindow = null;
    }
  }
};

// -----------------------------------------------------------------------------
// Open filter window
// -----------------------------------------------------------------------------

var FILTER_ID_NEWS                 =  "news";
var FILTER_ID_NEWS_DEFAULT         =  "news_default";
var FILTER_ID_DOMAIN_NEWS          =  "domain_news";
var FILTER_ID_EVENTS               =  "events";
var FILTER_ID_EVENTS_DEFAULT       =  "events_default";
var FILTER_ID_DOMAIN_EVENTS        =  "domain_events";
var FILTER_ID_FORUMS               =  "forums";
var FILTER_ID_FORUM_THEMAS         =  "forum_themas";
var FILTER_ID_FORUM_THEMA_MESSAGES =  "forum_thema_messages";
var FILTER_ID_GALLERIES            =  "imagegallery";
var FILTER_ID_NEWSLETTERS          =  "newsletters";
var FILTER_ID_NEWSLETTER_USERS     =  "newsletter_users";
var FILTER_ID_NEWSLETTERS2         =  "newsletters2";
var FILTER_ID_NEWSLETTER2_USERS    =  "newsletter2_users";
var FILTER_ID_NEWSLETTER2_EDITIONS =  "newsletter2_editions";
var FILTER_ID_MB_INFORMATION       =  "informations";
var FILTER_ID_JOBOFFERS            =  "joboffers";
var FILTER_ID_VISITORSBOOK         =  "visitorsbook";
var FILTER_ID_VCARDS               =  "vcards";
var FILTER_ID_ADBANNER             =  "adbanner";
var FILTER_ID_ADDRESSES            =  "addresses";
var FILTER_ID_ALLUSERS             =  "allusers";
var FILTER_ID_PRAYERREQUEST        =  "prayerrequest";
var FILTER_ID_MB2_ENTRY            =  "mb2_entry";
var FILTER_ID_MAGAZINE_EDITION     =  "magazine_edition";
var FILTER_ID_MAGAZINE_ARTICLE     =  "magazine_article";
var FILTER_ID_OFFERS               =  "offers";
var FILTER_ID_ASSETIMAGE           =  "asset_image";

function callFilter(sysPath, contentType) {

  if (contentType == null) {
    alert("Unknown content type");
    return false;
  }
	var pageUrl = null;
  var pageName = null;

	switch (contentType) {
		case FILTER_ID_NEWS :
		case FILTER_ID_NEWS_DEFAULT :
		case FILTER_ID_DOMAIN_NEWS :
			pageUrl = sysPath + "news_filter.html";
			pageName = "sysFilterNews";
			break;
		case FILTER_ID_EVENTS :
		case FILTER_ID_EVENTS_DEFAULT :
		case FILTER_ID_DOMAIN_EVENTS :
			pageUrl = sysPath + "events_filter.html";
			pageName = "sysFilterEvents";
			break;
		case FILTER_ID_GALLERIES :
			pageUrl = sysPath + "imagegalleries_filter.html";
			pageName = "sysFilterImageGalleries";
			break;
		case FILTER_ID_FORUMS :
			pageUrl = sysPath + "forums_filter.html";
			pageName = "sysFilterForums";
			break;
		case FILTER_ID_NEWSLETTERS :
			pageUrl = sysPath + "newsletters_filter.html";
			pageName = "sysFilterNewsletters";
			break;
		case FILTER_ID_NEWSLETTER_USERS :
			pageUrl = sysPath + "newsletter_users_filter.html";
			pageName = "sysFilterNewsletterUsers";
			break;
		case FILTER_ID_NEWSLETTERS2 :
			pageUrl = sysPath + "newsletters2_filter.html";
			pageName = "sysFilterNewsletters2";
			break;
		case FILTER_ID_NEWSLETTER2_EDITIONS :
			pageUrl = sysPath + "newsletter2_editions_filter.html";
			pageName = "sysFilterNewsletter2Editions";
			break;
		case FILTER_ID_NEWSLETTER2_USERS :
			pageUrl = sysPath + "newsletter2_users_filter.html";
			pageName = "sysFilterNewsletter2Users";
			break;
		case FILTER_ID_MB_INFORMATION :
			pageUrl = sysPath + "mb_informations_filter.html";
			pageName = "sysFilterExchangeInformations";
			break;
		case FILTER_ID_JOBOFFERS :
			pageUrl = sysPath + "joboffers_filter.html";
			pageName = "sysFilterJobOffers";
			break;
		case FILTER_ID_VISITORSBOOK :
			pageUrl = sysPath + "visitorsbook_filter.html";
			pageName = "sysFilterVisitorsBook";
			break;
		case FILTER_ID_VCARDS :
			pageUrl = sysPath + "vcards_filter.html";
			pageName = "sysFilterVCards";
			break;
		case FILTER_ID_ADBANNER :
			pageUrl = sysPath + "ad_banners_filter.html";
			pageName = "sysAdBanner";
			break;
		case FILTER_ID_ADDRESSES :
			pageUrl = sysPath + "address_filter.html";
			pageName = "sysAddresses";
			break;
		case FILTER_ID_ALLUSERS :
			pageUrl = sysPath + "sysadmin/allusers_filter.html";
			pageName = "sysAllUsers";
			break;
		case FILTER_ID_PRAYERREQUEST :
			pageUrl = sysPath + "prayerrequest_filter.html";
			pageName = "sysPrayerRequest";
			break;
		case FILTER_ID_MB2_ENTRY :
			pageUrl = sysPath + "mb2_entry_filter.html";
			pageName = "sysFilterMBEntries";
			break;
		case FILTER_ID_MAGAZINE_EDITION :
			pageUrl = sysPath + "magazine_edition_filter.html";
			pageName = "sysFilterMagazineEdition";
			break;
		case FILTER_ID_MAGAZINE_ARTICLE :
			pageUrl = sysPath + "magazine_article_filter.html";
			pageName = "sysFilterMagazineArticle";
			break;
		case FILTER_ID_OFFERS :
			pageUrl = sysPath + "offer_filter.html";
			pageName = "sysFilterOffers";
			break;
		case FILTER_ID_ASSETIMAGE :
			pageUrl = sysPath + "assetimage_filter.html";
			pageName = "sysFilterAssetImages";
			break;
		default : ;
	}
  openFilterWindow(pageUrl, contentType);

	return false;
}

function callFilterEx(sysPath, contentType, itemId) {
                                   
	var pageUrl, pageName, urlOptions = "";
	switch (contentType) {
		case FILTER_ID_FORUM_THEMAS :
			pageUrl = sysPath + "forum_themas_filter.html";
			pageName = "sysFilterForumThemas";
			urlOptions = "&f_forum_id=" + itemId;
			break;
		case FILTER_ID_FORUM_THEMA_MESSAGES :
			pageUrl = sysPath + "forum_thema_messages_filter.html";
			pageName = "sysFilterForumThemaMessages";
			urlOptions = "&f_thema_id=" + itemId;
			break;
		default :
	}

  if (isBlank(pageUrl)) {
    alert("Filter " + contentType + " - not implemented");
    return false;
  }

  if (top.window.GB_open) {
    var url = pageUrl + "?f_content_type=" + contentType + urlOptions;
    var winId = pageName;
    var width = 540;
    var height = 600;
    top.window.GB_open(url,winId,width,height,'');
  } 
  else {
  	var winFilter;
  	if (screen.width > 800) {
  		winFilter = window.open(pageUrl + "?f_content_type=" + contentType + urlOptions, pageName,
  			"width=520, height=600,  top=10, left=" + (screen.width - 540) + ", scrollbars=no, menubar=no");
  	} else {
  		winFilter = window.open(pageUrl + "?f_content_type=" + contentType + urlOptions, pageName,
  			"width=520, height=450,  top=10, left=" + (screen.width - 540) + ", scrollbars=no, menubar=no");
  	}
  	winFilter.opener = self;
  	winFilter.focus();  
  }
	return false;
}

function openFilterWindow(pageUrl, contentType) {

  if (isBlank(pageUrl)) {
    alert("Filter " + contentType + " - not implemented");
    return false;
  }
  if (contentType == null) {
    alert("Unknown content type");
    return false;
  }
  var pageName = "sysFilter" + trim(contentType);
  if (top.window.GB_open) {
    var width = 542;
    var height = 640;
    top.window.GB_open(pageUrl + "?f_content_type=" + contentType,pageName,width,height,'');
  } else {
    var winHeight = (screen.width > 800) ? 640 : 450;
    var winFilter = window.open(pageUrl + "?f_content_type=" + contentType, pageName,
	"width=540, height=" + winHeight + ", top=10, left=" + (screen.width - 560) + ", scrollbars=yes, menubar=no");
    if (winFilter != null) {
      winFilter.opener = self;
      winFilter.focus();
    } 
    return false;
  }
}

// -----------------------------------------------------------------------------
// Open MySite window
// -----------------------------------------------------------------------------

// used if opener should not be set
function callMySiteWindowNoOpener(path) {
	var width, height;
  if (screen.width > 1000) {
    width = 1024;
    height = 700;
  } else if (screen.width > 800) {
    width = 800;
    height = 700;
	} else {
    width = 600;
    height = 550;
	}
	return window.open(path, "Site" + ("" + Math.random()).substring(2), "width=" + width + ",height=" + height 
    + ",top=10,left=100,location=yes,scrollbars=yes,menubar=yes,toolbar=yes,resizable=yes,status=yes");
}

// used when opener set is required
function callMySiteWindow(path) {
  var win = callMySiteWindowNoOpener(path);
  if (win) {
    win.opener = self;
    win.focus();
  }
};

// -----------------------------------------------------------------------------
// Open category selection window in special modes
// -----------------------------------------------------------------------------
var MULTISELECT_ENABLED = 1;
var ALL_ITEMS_SELECTABLE = 2;
var ONESTEP_SELECT_ENABLED = 4;

function callSelectCategoryWindowEx2(sysPagesFolder, mySiteId, contentType, callbackId,
                                    selectedCategories, mode) {
	if (!selectedCategories || (trim(selectedCategories) == "all")) {
		selectedCategories = "";
	}

	var isMultiselectEnabled = ((mode & MULTISELECT_ENABLED) != 0);
	var isAllSelectable = ((mode & ALL_ITEMS_SELECTABLE) != 0);
	var isOneStepSelectEnabled = ((mode & ONESTEP_SELECT_ENABLED) != 0);
	if(top.window.GB_open){
    var url = sysPagesFolder + "config/select_categories.html?f_mysite_id=" + mySiteId
	    + "&f_content_type=" + contentType
			+ "&f_selected_categories=" + trim(selectedCategories)
			+ ( (trim(callbackId) != "") ? "&f_callback_id=" + trim(callbackId) : "")
			+ "&f_multiselect=" + (isMultiselectEnabled ? 1 : 0)
			+ "&f_all_selectable=" + (isAllSelectable ? 1 : 0)
			+ "&f_onestep_select=" + (isOneStepSelectEnabled ? 1 : 0)
			+ "&f_init_session=1";	 
    var winId = "SelectCategories";
    var width = 542;
    var height = 520;
    top.window.GB_open(url,winId,width,height,'');	
  }else{
    var win = window.open(sysPagesFolder + "config/select_categories.html?f_mysite_id=" + mySiteId
			+ "&f_content_type=" + contentType
			+ "&f_selected_categories=" + trim(selectedCategories)
			+ ( (trim(callbackId) != "") ? "&f_callback_id=" + trim(callbackId) : "")
			+ "&f_multiselect=" + (isMultiselectEnabled ? 1 : 0)
			+ "&f_all_selectable=" + (isAllSelectable ? 1 : 0)
			+ "&f_onestep_select=" + (isOneStepSelectEnabled ? 1 : 0)
			+ "&f_init_session=1", "SelectCategories", "toolbar=no, location=no, directories=no, status=no, menubar=0, scrollbars=yes, "
			+ "resizable=yes, top=10, left=" + ((screen.width - 542) / 2) + ", width=542, height=600");

    if (win != null) {
      win.opener = self;
      win.focus();
    }  
  }
}

// -----------------------------------------------------------------------------
// Open category selection window
// -----------------------------------------------------------------------------

function callSelectCategoryWindowEx(sysPagesFolder, mySiteId, contentType, callbackId, selectedCategories, mode) {
    return callSelectCategoryWindowEx2(sysPagesFolder, mySiteId, contentType, callbackId, 
    selectedCategories, mode | ONESTEP_SELECT_ENABLED);
}

function callSelectCategoryWindow(sysPagesFolder, mySiteId, contentType, callbackId, selectedCategories) {
    return callSelectCategoryWindowEx(sysPagesFolder, mySiteId, contentType, callbackId, selectedCategories, MULTISELECT_ENABLED);
}

// -----------------------------------------------------------------------------
// Open event category selection window
// -----------------------------------------------------------------------------

function callSelectEventCategoryWindow(sysPagesFolder, mySiteId, eventId) {
  if (top.window.GB_open) {
        var url = sysPagesFolder + "event_categories.html?f_mysite_id=" + mySiteId
		  + "&f_content_type=event&f_event_id=" + eventId + "&f_init_session=1&f_onestep_select=1";
        var winId = "SelectEventCategories";
        var width = 542;
        var height = 520;
        top.window.GB_open(url,winId,width,height,'');
  }else {
  	var win = window.open(sysPagesFolder + "event_categories.html?f_mysite_id=" + mySiteId
			+ "&f_content_type=event&f_event_id=" + eventId + "&f_init_session=1&f_onestep_select=1",
		"SelectEventCategories", "toolbar=no, location=no, directories=no, status=no, menubar=0, scrollbars=yes, "
			+ "resizable=yes, top=10, left=" + ((screen.width - 542) / 2) + ", width=542, height=600");
  	if (win != null) {
  		win.opener = self;
  		win.focus();
  	}  
  }
}

// -----------------------------------------------------------------------------
// Open mb2 category selection window
// -----------------------------------------------------------------------------

function callSelectMBEntryCategoryWindow(sysPagesFolder, mySiteId, entryId) {
if (top.window.GB_open) {
    // modified for use with greybox
    var url = sysPagesFolder + "mb2_entry_categories.html?f_mysite_id=" + mySiteId
		  + "&f_content_type=mb2&f_entry_id=" + entryId + "&f_init_session=1&f_onestep_select=1";
    var winId = "SelectMBEntryCategories";
    var width = 542;
    var height = 600;
    top.window.GB_open(url,winId,width,height,'');
}else{
	var win = window.open(sysPagesFolder + "mb2_entry_categories.html?f_mysite_id=" + mySiteId
			+ "&f_content_type=mb2&f_entry_id=" + entryId + "&f_init_session=1&f_onestep_select=1",
		"SelectMBEntryCategories", "toolbar=no, location=no, directories=no, status=no, menubar=0, scrollbars=yes, "
			+ "resizable=yes, top=10, left=" + ((screen.width - 542) / 2) + ", width=542, height=600");

	if (win != null) {
		win.opener = self;
		win.focus();
  }
}
}


// -----------------------------------------------------------------------------
// Open offer category selection window
// -----------------------------------------------------------------------------

function callSelectOfferCategoryWindow(sysPagesFolder, mySiteId, offerId) {
	var win = window.open(sysPagesFolder + "offer_categories.html?f_mysite_id=" + mySiteId
			+ "&f_content_type=offer&f_offer_id=" + offerId + "&f_init_session=1&f_onestep_select=1",
		"SelectOfferCategories", "toolbar=no, location=no, directories=no, status=no, menubar=0, scrollbars=yes, "
			+ "resizable=yes, top=10, left=" + ((screen.width - 542) / 2) + ", width=542, height=600");

	if (win != null) {
		win.opener = self;
		win.focus();
	}
}

// -----------------------------------------------------------------------------
// Open news item category selection window
// -----------------------------------------------------------------------------

function callSelectNewsItemCategoryWindow(sysPagesFolder, mySiteId, newsItemId) {
if (top.window.GB_open) {
  var url = sysPagesFolder + "news_categories.html?f_mysite_id=" + mySiteId
			+ "&f_content_type=news&f_newsitem_id=" + newsItemId + "&f_init_session=1&f_onestep_select=1";
  var winId = "SelectNewsItemCategories";
  var width = 542;
  var height = 600;
  top.window.GB_open(url,winId,width,height,'');
  
}else{
	var win = window.open(sysPagesFolder + "news_categories.html?f_mysite_id=" + mySiteId
			+ "&f_content_type=news&f_newsitem_id=" + newsItemId + "&f_init_session=1&f_onestep_select=1",
		"SelectNewsItemCategories", "toolbar=no, location=no, directories=no, status=no, menubar=0, scrollbars=yes, "
			+ "resizable=yes, top=10, left=" + ((screen.width - 542) / 2) + ", width=542, height=600");

	if (win != null) {
		win.opener = self;
		win.focus();
	}
}
}

// -----------------------------------------------------------------------------
// Open MySite category selection window
// -----------------------------------------------------------------------------

function callSelectMySiteCategoryWindow(sysPagesFolder, mySiteId, siteId) {
if (top.window.GB_open) {
  var url = sysPagesFolder + "site_categories.html?f_mysite_id=" + mySiteId
  			+ "&f_content_type=mysite&f_site_id=" + siteId + "&f_init_session=1&f_onestep_select=1";
  var winId = "SelectMySiteCategories";
  var width = 542;
  var height = 600;
  top.window.GB_open(url,winId,width,height,'');
  
}else{
  	var win = window.open(sysPagesFolder + "site_categories.html?f_mysite_id=" + mySiteId
  			+ "&f_content_type=mysite&f_site_id=" + siteId + "&f_init_session=1&f_onestep_select=1",
  		"SelectMySiteCategories", "toolbar=no, location=no, directories=no, status=no, menubar=0, scrollbars=yes, "
  			+ "resizable=yes, top=10, left=" + ((screen.width - 542) / 2) + ", width=542, height=600");
  
  	if (win != null) {
  		win.opener = self;
  		win.focus();
  	}
  }
  }

// -----------------------------------------------------------------------------
// Open forum category selection window
// -----------------------------------------------------------------------------

function callSelectForumCategoryWindow(sysPagesFolder, mySiteId, forumId) {
  if (top.window.GB_open) {
    var url = sysPagesFolder + "forum_categories.html?f_mysite_id=" + mySiteId
  			+ "&f_content_type=forum&f_forum_id=" + forumId + "&f_init_session=1&f_onestep_select=1";
    var winId = "SelectForumCategories";
    var width = 542;
    var height = 600;
    top.window.GB_open(url,winId,width,height,'');
  
  }else{
  	var win = window.open(sysPagesFolder + "forum_categories.html?f_mysite_id=" + mySiteId
  			+ "&f_content_type=forum&f_forum_id=" + forumId + "&f_init_session=1&f_onestep_select=1",
  		"SelectForumCategories", "toolbar=no, location=no, directories=no, status=no, menubar=0, scrollbars=yes, "
  			+ "resizable=yes, top=10, left=" + ((screen.width - 542) / 2) + ", width=542, height=600");
  
  	if (win != null) {
  		win.opener = self;
  		win.focus();
  	}
  }	
}

// -----------------------------------------------------------------------------
// Open newsletter category selection window
// -----------------------------------------------------------------------------

function callSelectNewsletterCategoryWindow(sysPagesFolder, mySiteId, newsletterId) {
	var win = window.open(sysPagesFolder + "newsletter_categories.html?f_mysite_id=" + mySiteId
			+ "&f_content_type=newsletter&f_newsletter_id=" + newsletterId + "&f_init_session=1&f_onestep_select=1",
		"SelectNewsletterCategories", "toolbar=no, location=no, directories=no, status=no, menubar=0, scrollbars=yes, "
			+ "resizable=yes, top=10, left=" + ((screen.width - 542) / 2) + ", width=542, height=600");

	if (win != null) {
		win.opener = self;
		win.focus();
	}
}

// -----------------------------------------------------------------------------
// Open newsletter 2 category selection window
// -----------------------------------------------------------------------------

function callSelectNewsletter2CategoryWindow(sysPagesFolder, mySiteId, newsletterId) {
if (top.window.GB_open) {
  var url = sysPagesFolder + "newsletter2_categories.html?f_mysite_id=" + mySiteId
  			+ "&f_content_type=newsletter&f_newsletter_id=" + newsletterId + "&f_init_session=1&f_onestep_select=1";
  var winId = "SelectNewsletter2Categories";
  var width = 542;
  var height = 600;
  top.window.GB_open(url,winId,width,height,'');
  
}else{
  	var win = window.open(sysPagesFolder + "newsletter2_categories.html?f_mysite_id=" + mySiteId
  			+ "&f_content_type=newsletter&f_newsletter_id=" + newsletterId + "&f_init_session=1&f_onestep_select=1",
  		"SelectNewsletter2Categories", "toolbar=no, location=no, directories=no, status=no, menubar=0, scrollbars=yes, "
  			+ "resizable=yes, top=10, left=" + ((screen.width - 542) / 2) + ", width=542, height=600");
  
  	if (win != null) {
  		win.opener = self;
  		win.focus();
  	}
  }
}

// -----------------------------------------------------------------------------
// Open address category selection window
// -----------------------------------------------------------------------------

function callSelectAddressCategoryWindow(sysPagesFolder, mySiteId, addressId) {
	var win = window.open(sysPagesFolder + "address_categories.html?f_mysite_id=" + mySiteId
			+ "&f_content_type=address&f_address_id=" + addressId + "&f_init_session=1&f_onestep_select=1",
		"SelectAddressCategories", "toolbar=no, location=no, directories=no, status=no, menubar=0, scrollbars=yes, "
			+ "resizable=yes, top=10, left=" + ((screen.width - 542) / 2) + ", width=542, height=600");

	if (win != null) {
		win.opener = self;
		win.focus();
	}
}

// -----------------------------------------------------------------------------
// Open resource category selection window
// -----------------------------------------------------------------------------

function callSelectResourceCategoryWindow(sysPagesFolder, mySiteId, resourcePath) {
  if (top.window.GB_open) {
        var url = sysPagesFolder + "resource_categories.html?f_mysite_id=" + mySiteId	+ "&f_content_type=resource&f_resource_path=" + resourcePath + "&f_init_session=1&f_onestep_select=1";
        var winId = "SelectResourceCategories";
        var width = 500;
        var height = 720;
        top.window.GB_open(url,winId,height,width,'');
  } 
  else {
  	var win = window.open(sysPagesFolder + "resource_categories.html?f_mysite_id=" + mySiteId
  			+ "&f_content_type=resource&f_resource_path=" + resourcePath + "&f_init_session=1&f_onestep_select=1",
  		"SelectResourceCategories", "toolbar=no, location=no, directories=no, status=no, menubar=0, scrollbars=yes, "
  			+ "resizable=yes, top=10, left=" + ((screen.width - 542) / 2) + ", width=542, height=600");
  	if (win != null) {
  		win.opener = self;
  		win.focus();
  	}
	}
}

// -----------------------------------------------------------------------------
// Open Preview News popup window
// -----------------------------------------------------------------------------

function previewNews(sysPreviewPagesFolder, mySitePath, itemId) {
	var win = window.open(sysPreviewPagesFolder + "news.html?f_action=show&f_newsitem_id=" + itemId
			+ "&f_page_url=" + mySitePath,
			"preview_news", "toolbar=no, location=no, directories=no, status=no, menubar=0, scrollbars=yes, "
			+ "resizable=yes, top=10, left=" + ((screen.width - 542) / 2) + ", width=542, height=600");

	if (win != null) {
		win.opener = self;
		win.focus();
	}
	return false;
}

// -----------------------------------------------------------------------------
// Open Preview Event popup window
// -----------------------------------------------------------------------------

function previewEvent(sysPreviewPagesFolder, mySitePath, itemId) {
	var win = window.open(sysPreviewPagesFolder + "event.html?f_action=show&f_event_id=" + itemId
			+ "&f_page_url=" + mySitePath,
			"preview_event", "toolbar=no, location=no, directories=no, status=no, menubar=0, scrollbars=yes, "
			+ "resizable=yes, top=10, left=" + ((screen.width - 542) / 2) + ", width=542, height=600");

	if (win != null) {
		win.opener = self;
		win.focus();
	}
	return false;
}

// -----------------------------------------------------------------------------
// Open Preview Offer popup window
// -----------------------------------------------------------------------------

function previewOffer(sysPreviewPagesFolder, mySitePath, itemId) {
	var win = window.open(sysPreviewPagesFolder + "offer.html?f_action=show&f_offer_id=" + itemId
			+ "&f_page_url=" + mySitePath,
			"preview_offer", "toolbar=no, location=no, directories=no, status=no, menubar=0, scrollbars=yes, "
			+ "resizable=yes, top=10, left=" + ((screen.width - 542) / 2) + ", width=542, height=600");

	if (win != null) {
		win.opener = self;
		win.focus();
	}
	return false;
}

// -----------------------------------------------------------------------------
// Get string formatted with given parameter
// -----------------------------------------------------------------------------

function getRes(message, param1) {
  return strReplace("" + message, "{0}", "" + param1, true);
}

// -----------------------------------------------------------------------------
// Get string formatted with given parameters
// -----------------------------------------------------------------------------

function getRes2(message, param1, param2) {
  message = getRes("" + message, "" + param1);
  return strReplace("" + message, "{1}", "" + param2, true);
}

// -----------------------------------------------------------------------------
// Get string formatted with given parameters
// -----------------------------------------------------------------------------

function getRes3(message, param1, param2, param3) {
  message = getRes2("" + message, "" + param1, "" + param2);
  return strReplace("" + message, "{2}", "" + param3, true);
}

// -----------------------------------------------------------------------------
// Get string formatted with given parameters
// -----------------------------------------------------------------------------

function getRes4(message, param1, param2, param3, param4) {
  message = getRes3("" + message, "" + param1, "" + param2, "" + param3);
  return strReplace("" + message, "{3}", "" + param4, true);
}

// -----------------------------------------------------------------------------
// Set the given form parameters for ordering and submit this form.
// Return false if all is set correctly (used on <a onclick="">) or
// return true if any form parameter is missing.
// The actual link is activated by this way.
// -----------------------------------------------------------------------------

function setOrder(form, orderBy, orderType) {
	if (!form)
		return true;
	if (!form.f_order_by)
		return true;
	if (!form.f_order_type)
		return true;

	form.f_order_by.value = orderBy;
	form.f_order_type.value = orderType;
	form.submit();

	return false;
}

// -----------------------------------------------------------------------------
// Set the given form parameters for ordering and submit this form.
// Return false if all is set correctly (used on <a onclick="">) or
// return true if any form parameter is missing.
// The actual link is activated by this way.
// Example of otherParams: { "param1": 19, "param2" : 20 }
// -----------------------------------------------------------------------------

function setOrderEx(form, orderBy, orderType, otherParams) {
	if (!form) {
		return true;
  }
	if (!form.f_order_by || !form.f_order_type) {
		return true;
  }

	form.f_order_by.value = orderBy;
	form.f_order_type.value = orderType;
  for (paramName in otherParams) {
    if (!form.elements[paramName]) {
      return true;
    }
    form.elements[paramName].value = otherParams[paramName];
  }
	form.submit();

	return false;
}

// -----------------------------------------------------------------------------
// Set given {action} to {form}.{actionParamName} parameter. If javascript function
// beforeDoWizzAction(...) exists then this function is called. If beforeDoWizzAction(...)
// returns true then {action} is submited if false action is refused. If
// beforeDoWizzAction(...) doesn't exist then submit is called directly.
// -----------------------------------------------------------------------------

function doWizzAction(form, actionParamName, action) {
    if (document.all) { // is IE
      window.external.AutoCompleteSaveForm(form);
    }
    var isStarted = startNoDoubleClick();
    if (isStarted) {
        if (window.beforeDoWizzAction && !window.beforeDoWizzAction(form, action)) {
            stopNoDoubleClick(true);
            return false;
        }
        eval("window.document." + form.name + "." + actionParamName + ".value = '" + action + "'");
        form.submit();
    }
	return isStarted;
}

// -----------------------------------------------------------------------------
// Set given {pageIndex} to {form}.f_next_wizz_page parameter. Value of parameter
// If javascript function beforeGoToWizzPage(...) exists then this function is called. If
// beforeGoToWizzPage(...) returns true then form is submited if false submit is refused.
// If beforeGoToWizzPage(...) doesn't exist then submit is called directly.
// -----------------------------------------------------------------------------

function goToWizzPage(form, pageIndex) {
    var isStarted = startNoDoubleClick();
    if (isStarted) {
        if (window.beforeGoToWizzPage && !window.beforeGoToWizzPage(form, pageIndex)) {
            stopNoDoubleClick(true);
            return false;
        }

        form.f_next_wizz_page.value = pageIndex;
        form.submit();
    }
	return isStarted;
}

// -----------------------------------------------------------------------------
// Set given {action} to {form}.{actionParamName} parameter. If javascript function
// beforeDoListAction(...) exists then this function is called. If beforeDoListAction(...)
// returns true then {action} is submited if false action is refused. If
// beforeDoListAction(...) doesn't exist then submit is called directly.
// -----------------------------------------------------------------------------

function doListAction(form, actionParamName, action, idParamName, itemId) {
  
    var isStarted = startNoDoubleClick();
    if (isStarted) {
        if (window.beforeDoListAction && !window.beforeDoListAction(form, action)) {
            if(window.stopNoDoubleClick) {
              stopNoDoubleClick(true);
            }
            return false;
        }

        //eval("document." + form.name + "." + actionParamName + ".value = '" + action + "'");
        if(document.forms[form.name]){
          eval("document." + form.name + "." + actionParamName + ".value = '" + action + "'");
          if (trim(idParamName) != '') {
            eval("document." + form.name + "." + idParamName + ".value = '" + itemId + "'");
          }
        }else{
          eval("top.window.document." + form.name + "." + actionParamName + ".value = '" + action + "'");
          if (trim(idParamName) != '') {
            eval("top.window.document." + form.name + "." + idParamName + ".value = '" + itemId + "'");
          }
        }


        form.submit();
    }
    return isStarted;
}

// -----------------------------------------------------------------------------
// Set given {action} to {form}.{actionParamName} parameter. If javascript function
// beforeDoListAction(...) exists then this function is called. If beforeDoListAction(...)
// returns true then {action} is submited if false action is refused. If
// beforeDoListAction(...) doesn't exist then submit is called directly.
// -----------------------------------------------------------------------------

function doListActionEx(form, actionParamName, action, idParamName_1, itemValue_1, idParamName_2, itemValue_2) {
    var isStarted = startNoDoubleClick();
    if (isStarted) {
        if (window.beforeDoListAction && !window.beforeDoListAction(form, action)) {
            stopNoDoubleClick(true);
            return false;
        }

        eval("document." + form.name + "." + actionParamName + ".value = '" + action + "'");
        if (trim(idParamName_1) != '') {
            eval("document." + form.name + "." + idParamName_1 + ".value = '" + itemValue_1 + "'");
        }
        if (trim(idParamName_2) != '') {
            eval("document." + form.name + "." + idParamName_2 + ".value = '" + itemValue_2 + "'");
        }

        form.submit();
    }
    return isStarted;
}
// -----------------------------------------------------------------------------
// Set given {action} to {form}.{actionParamName} parameter. If javascript function
// actionValidator(form, action) exists then this function is called and 
// given action is passed as parameter. If actionValidator(form, action)
// returns true then {action} is submited if false action is refused. If
// actionValidator(form, action) doesn't exist then submit is called directly.
// For given form are executed all registered validators (functions) and 
// if some of them returns falss then form submit is also refused.
//
// params example: [ {name: "f_param1", value: 1}, { name: "f_param2", value: 2}]
// -----------------------------------------------------------------------------

function doActionSubmit(form, actionParamName, action, actionValidator, params) {
    var isStarted = startNoDoubleClick();
    if (isStarted) {
        // find given form
        if (typeof form == "string") {
          form = document.forms[form];
        }
        // set requested parameters
        if (form.elements[actionParamName]) {
          form.elements[actionParamName].value = action;
        }
        if (params && params.length) {
          for (var i in params) {
            if (!params[i].name || !params[i].value) {
              continue; // ignore invalid param/value definition
            }
            if (form.elements[trim(params[i].name)]) {
              form.elements[trim(params[i].name)].value = params[i].value;
            }
          }
        }
        // execute a validators registered to given form and actionValidator if exists
        if (!executeValidators(form, action, actionValidator)) {
          stopNoDoubleClick(true);
          return false;
        }  
        form.submit();
    }
    return isStarted;
}

// -----------------------------------------------------------------------------
// execute a validators registered to given form 
// and passed actionValidator if exists
//
function executeValidators(form, action, actionValidator) {
  var valid = true;
  var validators = getRegisteredValidators(form.name), i;
  for (i = 0; valid && i < validators.length; i++) {
    valid &= validators[i](form, 'validate');
  }
  if (valid && typeof actionValidator == "function" && actionValidator) {
    valid &= actionValidator(form, action);
  }
  return valid;
}

// -----------------------------------------------------------------------------
// Register validator function that is called before form submit by method doActionSubmit()
// and validates given form fields.
// Validator has two parameters the first is used "form" that parameters are validated
// and the second is a submited action that is "validate". If any validator retuns false
// then form is not submitted otherwise form submit is done 
// after all validators are executed.
//
// @param formName name of form that fields are to be validated by validatorFunction
// @param validatorFunction the function that validates given form fields
//
// Validator function example: 
//   function validate(form, action) {
//     if (...) return false; // form submit is refused
//     return true; // form submit is accepted 
//   }
// -----------------------------------------------------------------------------
var registeredValidators = new Array();

function registerValidator(formName, validatorFunction) {
  var list = registeredValidators[formName];
  if (!list) {
    list = new Array();
  }
  if (typeof validatorFunction == "function") {
    list.push(validatorFunction);
    registeredValidators[formName] = list;
  }    
}

function getRegisteredValidators(formName) {
  var list = registeredValidators[(formName) ? formName : ''];
  return (list.length) ? list : new Array();
}



// -----------------------------------------------------------------------------
// Set given {pageIndex} to {form}.f_next_page parameter. If javascript
// function beforeGoToListPage(...) exists then this function is called. If
// beforeGoToListPage(...) returns true then form is submited if false submit is refused.
// If beforeGoToListPage(...) doesn't exist then submit is called directly.
// -----------------------------------------------------------------------------

function goToListPage(form, pageIndex) {
    var isStarted = startNoDoubleClick();
    if (isStarted) {
        if (window.beforeGoToListPage && !window.beforeGoToListPage(form, pageIndex)) {
            stopNoDoubleClick(true);
            return false;
        }

        form.f_next_page.value = pageIndex;
        form.submit();
    }
	return isStarted;
}

function goToListPageWithAction(form, pageIndex, action) {
    var isStarted = startNoDoubleClick();
    if (isStarted) {
        if (window.beforeGoToListPage && !window.beforeGoToListPage(form, pageIndex)) {
            stopNoDoubleClick(true);
            return false;
        }

        form.f_next_page.value = pageIndex;
        if (action != null) {
          form.f_action.value = action;
        }
        form.submit();
    }
	return isStarted;
}

// -----------------------------------------------------------------------------------
// Check if given email address is valid.
// Valid address is not empty and contains one '@' and at least one '.' character after '@'
// -----------------------------------------------------------------------------------
function checkEmailAddress(address) {
	if (trim(address) == "")
		return false;
	var index1 = address.indexOf("@");
	var index2 = address.indexOf(".", index1); // start after '@', address can have '.' before '@'
	if ((index1 < 0) || (index2 < 0))
		return false;
//	alert(address.substring(0, index1));
	if (trim(address.substring(0, index1)) == "")
		return false;
//	alert(address.substring(index1 + 1, index2));
	if (trim(address.substring(index1 + 1, index2)) == "")
		return false;
//	alert(address.substring(index2 + 1));
	if (trim(address.substring(index2 + 1)) == "")
		return false;

	return true;
}

// -----------------------------------------------------------------------------------
// Define Gallery data value object
// -----------------------------------------------------------------------------------

function GalleryObject_toString() {
	return "{id=" + this.id + "}{title=" + this.title +
	       "}{subtitle=" + this.subtitle + "}{description=" + this.description + "}";
}

function GalleryObject() {
	this.id = '';
	this.title = '';
	this.subtitle = '';
	this.description = '';

	this.toString = GalleryObject_toString;
}

// -----------------------------------------------------------------------------------
// Get field Id, based on next parameters create Gallery data value object and if opener
// contains function gallerySelected(fieldId, galleryObject) then call it with given parameters.
//
// parameters: fieldId, gallery-attr1-name, gallery-attr1-value[, gallery-attr2-name, gallery-attr2-value[, ...]]
// -----------------------------------------------------------------------------------

function updateGallery() {
	var i, gallery = new GalleryObject(), myCommand, paramValue;

	for (i = 1; i < arguments.length; i += 2) {
	    paramValue = arguments[i + 1];
	    if ((paramValue.indexOf("document.") >= 0) && eval(paramValue)) {
	        myCommand = "gallery." + arguments[i] + "=" + paramValue + ".value;";
	    } else {
	        myCommand = "gallery." + arguments[i] + "='" + paramValue + "';";
	    }
	    eval(myCommand);
	}

	if (top.opener && top.opener.window && top.opener.window.gallerySelected) {
		top.opener.window.gallerySelected(arguments[0], gallery);
	}else if(top && top.window && top.window.gallerySelected){
    top.window.gallerySelected(arguments[0], gallery);
  }

	return true;
}

// -----------------------------------------------------------------------------------
// Open Image gallery selection window
// -----------------------------------------------------------------------------------

function callSelectImageGalleryWindow(sysPagesFolder, mySiteId, callbackId) {
if (top.window.GB_open) {
    // modified for use with greybox
    var url = sysPagesFolder + "config/select_imagegallery.html?f_mysite_id=" + mySiteId
			  + "&f_callback_id=" + callbackId;
    var winId = "SelectImageGallery";
    var width = 542;
    var height = 600;
    top.window.GB_open(url,winId,width,height,'');
}else{
	  var win = window.open(sysPagesFolder + "config/select_imagegallery.html?f_mysite_id=" + mySiteId
			  + "&f_callback_id=" + callbackId,
		  "SelectImageGallery", "toolbar=no, location=no, directories=no, status=no, menubar=0, scrollbars=yes, "
			  + "resizable=yes, top=10, left=" + ((screen.width - 542) / 2) + ", width=542, height=600");

	  if (win != null) {
		  win.opener = self;
		  win.focus();
	  }
  }
}

// -----------------------------------------------------------------------------
// Open image gallery category selection window
// -----------------------------------------------------------------------------

function callSelectImageGalleryCategoryWindow(sysPagesFolder, mySiteId, galleryId) {
  if (top.window.GB_open) {
    // modified for use with greybox
    var url = sysPagesFolder + "imagegalleries_categories.html?f_mysite_id=" + mySiteId
  		+ "&f_content_type=imagegallery&f_gallery_id=" + galleryId + "&f_init_session=1&f_onestep_select=1";
    var winId = "SelectImageGalleryCategories";
    var width = 542;
    var height = 520;
    top.window.GB_open(url,winId,width,height,'');
  } else {
    // original popup is opened
  	var win = window.open(sysPagesFolder + "imagegalleries_categories.html?f_mysite_id=" + mySiteId
  			+ "&f_content_type=imagegallery&f_gallery_id=" + galleryId + "&f_init_session=1&f_onestep_select=1",
  		"SelectImageGalleryCategories", "toolbar=no, location=no, directories=no, status=no, menubar=0, scrollbars=yes, "
  			+ "resizable=yes, top=10, left=" + ((screen.width - 542) / 2) + ", width=542, height=600");
  
  	if (win != null) {
  		win.opener = self;
  		win.focus();
  	}
  }
}

// -----------------------------------------------------------------------------
// Open worship category selection window
// -----------------------------------------------------------------------------

function callSelectWorshipCategoryWindow(sysPagesFolder, mySiteId, worshipId) {
if (top.window.GB_open) {
    // modified for use with greybox
    var url = sysPagesFolder + "worship_categories.html?f_mysite_id=" + mySiteId
  			+ "&f_content_type=worship&f_worship_id=" + worshipId + "&f_init_session=1&f_onestep_select=1";
    var winId = "SelectWorshipCategories";
    var width = 542;
    var height = 600;
    top.window.GB_open(url,winId,width,height,'');
}else{
  	var win = window.open(sysPagesFolder + "worship_categories.html?f_mysite_id=" + mySiteId
  			+ "&f_content_type=worship&f_worship_id=" + worshipId + "&f_init_session=1&f_onestep_select=1",
  		"SelectWorshipCategories", "toolbar=no, location=no, directories=no, status=no, menubar=0, scrollbars=yes, "
  			+ "resizable=yes, top=10, left=" + ((screen.width - 542) / 2) + ", width=542, height=600");
  
  	if (win != null) {
  		win.opener = self;
  		win.focus();
  	}
  }
}

// -----------------------------------------------------------------------------
// Open default worship category selection window
// -----------------------------------------------------------------------------

function callSelectDefaultWorshipCategoryWindow(sysPagesFolder, mySiteId, worshipId) {
if (top.window.GB_open) {
    // modified for use with greybox
    var url = sysPagesFolder + "worship_default_categories.html?f_mysite_id=" + mySiteId
  			+ "&f_content_type=worship&f_worship_id=" + worshipId + "&f_init_session=1&f_onestep_select=1";
    var winId = "SelectDefaultWorshipCategories";
    var width = 542;
    var height = 600;
    top.window.GB_open(url,winId,width,height,'');
}else{
  	var win = window.open(sysPagesFolder + "worship_default_categories.html?f_mysite_id=" + mySiteId
  			+ "&f_content_type=worship&f_worship_id=" + worshipId + "&f_init_session=1&f_onestep_select=1",
  		"SelectDefaultWorshipCategories", "toolbar=no, location=no, directories=no, status=no, menubar=0, scrollbars=yes, "
  			+ "resizable=yes, top=10, left=" + ((screen.width - 542) / 2) + ", width=542, height=600");
  
  	if (win != null) {
  		win.opener = self;
  		win.focus();
  	}
  }  
}

// -----------------------------------------------------------------------------
// Open asset image category selection window
// -----------------------------------------------------------------------------

function callSelectAssetImageCategoryWindow(sysPagesFolder, mySiteId, assetId) {
if (top.window.GB_open) {
    // modified for use with greybox
    var url = sysPagesFolder + "assetimage_categories.html?f_mysite_id=" + mySiteId
  			+ "&f_content_type=asset_image&f_asset_id=" + assetId + "&f_init_session=1&f_onestep_select=1";
    var winId = "SelectAssetImageCategories";
    var width = 542;
    var height = 600;
    top.window.GB_open(url,winId,width,height,'');
}else{
  	var win = window.open(sysPagesFolder + "assetimage_categories.html?f_mysite_id=" + mySiteId
  			+ "&f_content_type=asset_image&f_asset_id=" + assetId + "&f_init_session=1&f_onestep_select=1",
  		"SelectAssetImageCategories", "toolbar=no, location=no, directories=no, status=no, menubar=0, scrollbars=yes, "
  			+ "resizable=yes, top=10, left=" + ((screen.width - 542) / 2) + ", width=542, height=600");
  
  	if (win != null) {
  		win.opener = self;
  		win.focus();
  	}
  }
}

// -----------------------------------------------------------------------------
// Open send news window
// -----------------------------------------------------------------------------

function callSendNewsWindow(sysPagesFolder, newsItemId) {
if (top.window.GB_open) {
    // modified for use with greybox
    var url = sysPagesFolder + "send_news.html?f_action=send&f_newsitem_id=" + newsItemId;
    var winId = "SendNews";
    var width = 542;
    var height = 600;
    top.window.GB_open(url,winId,width,height,'');
}else{
	var win = window.open(sysPagesFolder + "send_news.html?f_action=send&f_newsitem_id=" + newsItemId,
		"SendNews", "toolbar=no, location=no, directories=no, status=no, menubar=0, scrollbars=yes, "
			+ "resizable=yes, top=10, left=" + ((screen.width - 542) / 2) + ", width=542, height=600");

	if (win != null) {
		win.opener = self;
		win.focus();
	}
}
}

// -----------------------------------------------------------------------------
// Send News directly and open Send News popup window
// -----------------------------------------------------------------------------

function callSendNewsDirectWindow(sysPagesFolder, newsItemId, mySiteId) {
	var win = window.open(sysPagesFolder + "send_news.html?f_action=send_submit&f_newsitem_id=" + newsItemId
    + "&f_target_mysite_id=" + mySiteId,
		"SendNews", "toolbar=no, location=no, directories=no, status=no, menubar=0, scrollbars=yes, "
			+ "resizable=yes, top=10, left=" + ((screen.width - 542) / 2) + ", width=542, height=600");

	if (win != null) {
		win.opener = self;
		win.focus();
	}
}

// -----------------------------------------------------------------------------
// Open send events window
// -----------------------------------------------------------------------------

function callSendEventsWindow(sysPagesFolder, eventId) {
	/* var win = window.open(sysPagesFolder + "send_events.html?f_action=send&f_event_id=" + eventId,
		"SendEvents", "toolbar=no, location=no, directories=no, status=no, menubar=0, scrollbars=yes, "
			+ "resizable=yes, top=10, left=" + ((screen.width - 542) / 2) + ", width=542, height=600");

	if (win != null) {
		win.opener = self;
		win.focus();
	} */
        var url = sysPagesFolder + "send_events.html?f_action=send&f_event_id=" + eventId;
        var winId = "SendEvents";
        var width = 500;
        var height = 480;
        top.window.GB_open(url,winId,width,height,'');
}

// -----------------------------------------------------------------------------
// Open JobOffer category selection window
// -----------------------------------------------------------------------------

function callSelectJobOfferCategoryWindow(sysPagesFolder, mySiteId, worshipId) {
	var win = window.open(sysPagesFolder + "joboffers_categories.html?f_mysite_id=" + mySiteId
			+ "&f_content_type=joboffer&f_joboffer_id=" + worshipId + "&f_init_session=1&f_onestep_select=1",
		"SelectJobOfferCategories", "toolbar=no, location=no, directories=no, status=no, menubar=0, scrollbars=yes, "
			+ "resizable=yes, top=10, left=" + ((screen.width - 542) / 2) + ", width=542, height=600");

	if (win != null) {
		win.opener = self;
		win.focus();
	}
};

// -----------------------------------------------------------------------------
// Open MySites selection window
// -----------------------------------------------------------------------------

var MYSITE_FILTER_ALL_NOT_SYND = "all_not_synd"; // all MySites except of syndication candidates
var MYSITE_FILTER_ALL = "all";                  // all MySites
var MYSITE_FILTER_ALL_PUBLIC = "all_public"; // all public MySites
var MYSITE_FILTER_USER_ACTIONS = "user_actions"; // MySites where current user has any user actions

// binary coded flags for excluding type. Flags, not MySite IDs (!)
var MYSITE_FILTER_EXCLUDE_NONE = 0;
var MYSITE_FILTER_EXCLUDE_ROOT = 1;
var MYSITE_FILTER_EXCLUDE_DS   = 2;

function callSelectMySiteWindow(sysPagesFolder, mySiteId, selectedIds, callbackId,
         isMultiselectEnabled, mySiteFilter, mySiteFilterExclude) {
  if (top.window.GB_open) {
    var url = sysPagesFolder + "config/select_mysites2.html?f_mysite_id=" + mySiteId
	        + "&f_selected_mysite_ids=" + trim(selectedIds)
	        + ( (trim(callbackId) != "") ? "&f_callback_id=" + trim(callbackId) : "")
	        + "&f_multiselect=" + ( ((isMultiselectEnabled == 1) || isMultiselectEnabled) ? 1 : 0)
	        + "&f_init_session=1&f_mysite_filter=" + mySiteFilter + "&f_mysite_filter_exclude=" + mySiteFilterExclude;
    top.window.GB_open(url,"SelectMySites",542,600,''); 
  }else{
    var winTop = 40;
    var winLeft = ((screen.width - 542) / 2) + 30;
    var win = window.open(sysPagesFolder + "config/select_mysites.html?f_mysite_id=" + mySiteId
	        + "&f_selected_mysite_ids=" + trim(selectedIds)
	        + ( (trim(callbackId) != "") ? "&f_callback_id=" + trim(callbackId) : "")
	        + "&f_multiselect=" + ( ((isMultiselectEnabled == 1) || isMultiselectEnabled) ? 1 : 0)
	        + "&f_init_session=1&f_mysite_filter=" + mySiteFilter + "&f_mysite_filter_exclude=" + mySiteFilterExclude,
           "SelectMySites", "toolbar=no, location=no, directories=no, status=no, menubar=0, scrollbars=yes, "
            + "resizable=yes, top=" + winTop + ",left=" + winLeft + ", width=542, height=600");
    if (win != null) {
		  win.opener = self;
		  win.focus();
    }
  }
}

function callSelectMySiteWindow2(sysPagesFolder, mySiteId, selectedIds, callbackId,
         isMultiselectEnabled, mySiteFilter, mySiteFilterExclude) {
  var url = sysPagesFolder + "config/select_mysites2.html?f_mysite_id=" + mySiteId
	    + "&f_selected_mysite_ids=" + trim(selectedIds)
	    + ( (trim(callbackId) != "") ? "&f_callback_id=" + trim(callbackId) : "")
	    + "&f_multiselect=" + ( ((isMultiselectEnabled == 1) || isMultiselectEnabled) ? 1 : 0)
	    + "&f_init_session=1&f_mysite_filter=" + mySiteFilter + "&f_mysite_filter_exclude=" + mySiteFilterExclude;
  var winId = "SelectMySites";
  var width = 542;
  var height = 480;
  top.window.GB_open(url,winId,width,height,'');
}


// -----------------------------------------------------------------------------
// Open MySite Group selection window
// -----------------------------------------------------------------------------
/*
function callSelectMySiteGroupWindow(sysPagesFolder, mySiteId, callbackId) {
  var winTop = 40;
  var winLeft = ((screen.width - 542) / 2) + 30;
	var win = window.open(sysPagesFolder + "config/select_mysitegroup.html?f_mysite_id=" + mySiteId
	        + ( (trim(callbackId) != "") ? "&f_callback_id=" + trim(callbackId) : "")
	        + "&f_init=1",
           "SelectMySiteGroup", "toolbar=no, location=no, directories=no, status=no, menubar=0, scrollbars=yes, "
            + "resizable=yes, top=" + winTop + ",left=" + winLeft + ", width=542, height=600");
	if (win != null) {
		win.opener = self;
		win.focus();
	}
}
*/
function callSelectMySiteGroupWindow(sysPagesFolder, mySiteId, callbackId) {
  if (top.window.GB_open) {
    var url = sysPagesFolder + "config/select_mysitegroup.html?f_mysite_id=" + mySiteId
  	        + ( (trim(callbackId) != "") ? "&f_callback_id=" + trim(callbackId) : "") + "&f_init=1";
    top.window.GB_open(url,"SelectMySiteGroup",542,600,''); 
  }else{
    var winTop = 40;
    var winLeft = ((screen.width - 542) / 2) + 30;
  	var win = window.open(sysPagesFolder + "config/select_mysitegroup.html?f_mysite_id=" + mySiteId
  	        + ( (trim(callbackId) != "") ? "&f_callback_id=" + trim(callbackId) : "")
  	        + "&f_init=1",
             "SelectMySiteGroup", "toolbar=no, location=no, directories=no, status=no, menubar=0, scrollbars=yes, "
              + "resizable=yes, top=" + winTop + ",left=" + winLeft + ", width=542, height=600");
  	if (win != null) {
  		win.opener = self;
  		win.focus();
		}
	}
}
// -----------------------------------------------------------------------------
// Open VCard selection window
// -----------------------------------------------------------------------------

function callSelectVCardWindow(sysPagesFolder, mySiteId, vCardId, vCardType, callbackId) {
	var win = window.open(sysPagesFolder + "config/select_vcards.html?f_mysite_id=" + mySiteId
	        + "&f_vcard_id=" + vCardId + "&f_vcard_type=" + vCardType
	        + ( (trim(callbackId) != "") ? "&f_callback_id=" + trim(callbackId) : "")
	        + "&f_init_session=1",
        "SelectVCards", "toolbar=no, location=no, directories=no, status=no, menubar=0, scrollbars=yes, "
            + "resizable=yes, top=10,left=" + ((screen.width - 542) / 2) + ", width=542, height=600");
	if (win != null) {
		win.opener = self;
		win.focus();
	}
}

// -----------------------------------------------------------------------------
// Change Admin MySite - submit form_select_mysite_and_action defined in admin_select_mysite_combo
function submitChangedAdminMySite(newAdminMySiteId) {
  if (isBlank(newAdminMySiteId)) {
    // invalid parameter
    return;
  }
  var form = document.form_select_mysite_and_action;
  if (form.f_admin_mysite_id) {
    form.f_admin_mysite_id.value = newAdminMySiteId;
    form.submit();
  }
}

function submitChangedAdminMySiteAndAction(newAdminMySiteId, newAction) {
  if (isBlank(newAdminMySiteId) || isBlank(newAction)) {
    // invalid parameters
    return;
  }
  var form = document.form_select_mysite_and_action;
  if (!form.f_admin_mysite_id) {
    // missing form field
    return;
  }
  form.f_admin_mysite_id.value = newAdminMySiteId;
  if (form.f_new_page) {
    form.f_new_page.value = newAction;
  }
  form.submit();
}

// -----------------------------------------------------------------------------
// Open MySite user selection window
// -----------------------------------------------------------------------------

function callSelectMySiteUserWindow(sysPagesFolder, mySiteId, userName, callbackId) {
    var win = window.open(sysPagesFolder + "config/select_mysite_user.html"
            + "?f_mysite_id=" + mySiteId + "&f_user_name=" + userName
            + ( (trim(callbackId) != "") ? "&f_callback_id=" + trim(callbackId) : "")
	        + "&f_init_session=1",
        "SelectUser", "toolbar=no, location=no, directories=no, status=no, menubar=0, scrollbars=yes, "
            + "resizable=yes, top=10,left=" + ((screen.width - 542) / 2) + ", width=542, height=600");
	if (win != null) {
		win.opener = self;
		win.focus();
	}
}

// -----------------------------------------------------------------------------
// Open Information category selection window
// -----------------------------------------------------------------------------

function callSelectInformationCategoryWindow(sysPagesFolder, mySiteId, informationId) {
	var win = window.open(sysPagesFolder + "mb_information_categories.html?f_mysite_id=" + mySiteId
			+ "&f_content_type=information&f_information_id=" + informationId + "&f_init_session=1&f_onestep_select=1",
		"SelectInformationCategories", "toolbar=no, location=no, directories=no, status=no, menubar=0, scrollbars=yes, "
			+ "resizable=yes, top=10, left=" + ((screen.width - 542) / 2) + ", width=542, height=600");

	if (win != null) {
		win.opener = self;
		win.focus();
	}
}

// -----------------------------------------------------------------------------
// Open User Configuration window
// -----------------------------------------------------------------------------

function callUserConfiguration(mySiteId, userName) {
  if (top.window.GB_open) {
      var url = context.sp + context.dspagesfolder + "sites_user_config.html?f_mysite_id=" + mySiteId + "&f_username=" + userName;
      var winId = "mySiteUserConfiguration";
      var width = 635;
      var height = 800;
      top.window.GB_open(url,winId,width,height,'');
  } 
  else {
	var win = window.open(context.sp + context.dspagesfolder + "sites_user_config.html?f_mysite_id=" + mySiteId
			+ "&f_username=" + userName,
			"mySiteUserConfiguration", "toolbar=no, location=no, directories=no, status=no, menubar=0, scrollbars=yes, "
			+ "resizable=yes, top=10, left=" + (screen.width - 645) + ", width=635, height=" + ((screen.width > 800) ? 800 : 600));

	if (win != null) {
		win.opener = self;
		win.focus();
	}  
  }
  return false;
}


// -----------------------------------------------------------------------------
// Show date pattern in given input if its value is empty
// -----------------------------------------------------------------------------

function showDatePattern(element) {
  if(trim(element.value) == '') { 
    element.value='TT.MM.JJJJ';
  }
}

// -----------------------------------------------------------------------------
// Hide date pattern in given input if its value is valid date pattern
// -----------------------------------------------------------------------------

function hideDatePattern(element) {
  var date = trim(element.value);
  if((date == '') || (date.toUpperCase() == 'TT.MM.JJJJ')) { 
    element.value='';
  }
}

// -----------------------------------------------------------------------------
// Show time pattern in given input if its value is empty
// -----------------------------------------------------------------------------

function showTimePattern(element) {
  if(trim(element.value) == '') { 
    element.value='SS:MM';
  }
}

// -----------------------------------------------------------------------------
// Hide time pattern in given input if its value is valid time pattern
// -----------------------------------------------------------------------------

function hideTimePattern(element) {
  var date = trim(element.value);
  if((date == '') || (date.toUpperCase() == 'SS:MM')) { 
    element.value='';
  }
};

// -----------------------------------------------------------------------------
// Functions for prevent the doubleclick. Start point for mechanism is function
// startNoDoubleClick(). For start/stop additional actions define own functions
// onStartNoDoubleClick() and onStopNoDoubleClick(), for show other message then
// default define onClickDisabled()
// -----------------------------------------------------------------------------

//
var dsDoubleClickTimerID = null;
var dsDoubleClickTimerRunning = false;
var dsDoubleClickStartTime = new Date(1970, 1, 1, 0, 0, 0, 0);
var dsDoubleClickMinTimeDiff = 5000;

// Start timer checking double click.
// Return true if is started successufuly, false if not started because check is
// already running.
function startNoDoubleClick() {
  var isStarted = false;
  if (dsDoubleClickTimerRunning) {
    if (window.onClickDisabled) {
      window.onClickDisabled();
    } else {
      alert("Die Aktion wird bereits ausgeführt.");
    }
    isStarted = false;
  } else {
    // Make sure the clock is stopped
    stopNoDoubleClick(false);
    if (window.onStartNoDoubleClick) {
      window.onStartNoDoubleClick();
    }
    dsDoubleClickStartTime = new Date();
    dsDoubleClickTimerID = setInterval("checkNoDoubleClick()", 1000);
    dsDoubleClickTimerRunning = true;
    isStarted = true;
  }

  return isStarted;
}

// check double click (called by timer for checking double click)
function checkNoDoubleClick() {
  var timeDiff = (new Date() - dsDoubleClickStartTime);
  var nextClickEnabled = (timeDiff > dsDoubleClickMinTimeDiff);
  if (nextClickEnabled) {
    stopNoDoubleClick(true);
  }
}

// Get true is no-double click is active, false otherwise (called by methods 
// to know whether questions should be skiped when no-double click is active)
function isNoDoubleClickActive() {
  var timeDiff = (new Date() - dsDoubleClickStartTime);
  var nextClickEnabled = !dsDoubleClickTimerRunning && (timeDiff > dsDoubleClickMinTimeDiff);
  return !nextClickEnabled;
}

// stop timer checking double click
function stopNoDoubleClick(callEvent) {
  if (dsDoubleClickTimerRunning) {
    clearInterval(dsDoubleClickTimerID);
    dsDoubleClickTimerRunning = false;
  }

  if (callEvent && window.onStopNoDoubleClick) {
    window.onStopNoDoubleClick();
  }
}

// -----------------------------------------------------------------------------
// Get data from Clipboard 
// @deprecated - moved to htmlarea.js
// -----------------------------------------------------------------------------
function getClipboard() {
  if (window.clipboardData) {
    return(window.clipboardData.getData('Text'));
  } else { 
    netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
    var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
    if (!clip) return;
    var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
    if (!trans) return;
    trans.addDataFlavor('text/unicode');
    clip.getData(trans,clip.kGlobalClipboard);
    var str = new Object();
    var len = new Object();
    try { trans.getTransferData('text/unicode',str,len); }
    catch(error) { return; }
    if (str) {
      if (Components.interfaces.nsISupportsWString) str=str.value.QueryInterface(Components.interfaces.nsISupportsWString);
      else if (Components.interfaces.nsISupportsString) str=str.value.QueryInterface(Components.interfaces.nsISupportsString);
      else str = null;
    }
    if (str) return(str.data.substring(0,len.value / 2));
  }
  return;
};

// -----------------------------------------------------------------------------
// Set fields flag disabled.
// fieldsIds: array of fields' ids
// disabled: value of disabled flag
// -----------------------------------------------------------------------------

function setFieldsDisabledById(fieldsIds, disabled) {
  for (i = 0; i < fieldsIds.length; i++) {
    document.getElementById(fieldsIds[i]).disabled = disabled;
  }
  return true;
};

// -----------------------------------------------------------------------------
// Set actions' buttons flag disabled.
// actionsIds: array of actions' ids
// disabled: value of disabled flag
// -----------------------------------------------------------------------------
var ACTION_ID_SAVE            = "save";
var ACTION_ID_SAVE_AND_CLOSE  = "save_close";

function setActionDisabledById(actionsIds, disabled) {
  var objRef, actionId;
  for (i = 0; i < actionsIds.length; i++) {
    actionId = actionsIds[i];
    // set action state
    if (self.setWizzActionState) {
      setWizzActionState(actionId, !disabled);
    }
    // enable/disable buttons
    objRef = document.getElementById('btn_' + actionId + '_on');
    if (objRef) {
      objRef.disabled = disabled;
    }
    objRef = document.getElementById('btn_' + actionId + '_off');
    if (objRef) {
      objRef.disabled = disabled;
    }
  }
  return true;
};

// -----------------------------------------------------------------------------
// Online Help
// -----------------------------------------------------------------------------

var adminHelpPage = null;

function callAdminHelpWindow() {
  if (adminHelpPage == null) {
    return;
  }

  var leftPosition = screen.width - 530;
  var winHeight = ( (screen.width > 800) ? 700 : 550 );

  var path = context.sp + adminHelpPage;
  if (this.actWin) {
    if (path.indexOf("#") < 0) {
      path += "#";
    }
    path += "_" + actWin;
  }
  // alert("Help path: " + path);
  var win = window.open(path, "DSHelp", "width=500, height=" + winHeight + ", top=5, left=" + leftPosition 
    + ", toolbar=no,location=no,directories=no,status=yes,menubar=0,scrollbars=yes,resizable=yes");

  if (win != null) {
    win.opener = self;
    win.focus();
  }
}

// -----------------------------------------------------------------------------
// getScrollXY
// -----------------------------------------------------------------------------
function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    // Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    // DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement &&
      ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    // IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

// -----------------------------------------------------------------------------
// Get array without blank strings
// -----------------------------------------------------------------------------
function getStringArrayWithoutBlanks(array) {
   var result = [];
   for (var i = 0; i < array.length; i++) {
      var item = trim(array[i]);
      if (item.length > 0) {
        result[result.length] = item;
      }
    }
    return result;
}

// -----------------------------------------------------------------------------
// Get value of checked item of given radiogroup
// -----------------------------------------------------------------------------
function getRadioValue(radioGroup) {
	var i, choice = "";
	for (i = 0; i < radioGroup.length; i++) {
	   if (radioGroup[i].checked) {
	     choice = radioGroup[i].value;
	     break;
	   }
	}
	return choice;
};

// -----------------------------------------------------------------------------
// Get string with some "standard" non-Latin1 characters mapped to Latin1 counterparts
// -----------------------------------------------------------------------------

// mapping: pairs [source, destination] character codes
var mapTableLatin1 = [ [8211, 45], [8212, 45], [8216, 39], [8217, 39], [8218, 39], [8219, 39], 
  [8220, 34], [8221, 34], [8222, 34], [8242, 39], [8243, 34], [8249, 39], [8250, 39],
  [256, 65], [257, 97], [258, 65], [259, 97], [260, 65], [261, 65], [262, 67],
  [263, 99], [264, 67], [265, 99], [266, 67], [267, 99], [268, 67], [269, 99], 
  [270, 68], [271, 100], [272, 68], [273, 100], [274, 69], [275, 101],
  [276, 69], [277, 101], [278, 69], [279, 101], [280, 69], [281, 101], [282, 69], [283, 101],
  [284, 71], [284, 71], [285, 103], [286, 71], [287, 103], [288, 71], [289, 103],
  [290, 71], [291, 103], [292, 72], [293, 104], [294, 72], [295, 104], [296, 73],
  [297, 105], [298, 73], [299, 105], [300, 73], [301, 105], [302, 73], [303, 105],
  [304, 73], [305, 105], [306, 73], [307, 105], [308, 74], [309, 106], [310, 75],
  [311, 107], [312, 75], [313, 76], [314, 108], [315, 76], [316, 108], [317, 76],
  [318, 108], [319, 76], [320, 108], [321, 76], [322, 108], [323, 78], [324, 110],
  [325, 78], [326, 110], [327, 78], [328, 110], [329, 110], [330, 78], [331, 110],
  [332, 79], [333, 111], [334, 79], [335, 111], [336, 79], [337, 111], [338, 214],
  [339, 246], [340, 82], [341, 114], [342, 82], [343, 114], [344, 82], [345, 114],
  [346, 83], [347, 115], [348, 83], [349, 115], [350, 83], [351, 115], [352, 83],
  [353, 115], [354, 84], [355, 116], [356, 84], [357, 116], [358, 84], [359, 116],
  [360, 85], [361, 117], [362, 85], [363, 117], [364, 85], [365, 117], [366, 85],
  [367, 117], [368, 220], [369,	252], [370, 85], [371, 117], [372, 87], [373, 119],
  [374, 89], [375, 121], [376, 89], [377, 90], [378, 122], [379, 90], [380,	122],
  [381, 90], [382, 122]
 ];
  
function mapCharactersToLatin1(str) {
  var results = [];
  for (i = 0; i < str.length; i++) {
    var code = str.charCodeAt(i);
//  alert(str.charAt(i) + " (" + code + ")");
    for (j = 0; j < mapTableLatin1.length; j++) {
      var entry = mapTableLatin1[j];
      if (entry[0] == code) {
        code = entry[1];
        break;
      }
    }
    results.push(String.fromCharCode(code));
  }
  var res = results.join('');
  return res;
}

// -----------------------------------------------------------------------------
// Format current date and time according to format DD.MM.YYYY HH:MM
// -----------------------------------------------------------------------------
function formatCurrentDateTime() {
  var now = new Date();
  return ((now.getDate() < 10) ? "0" + now.getDate() : now.getDate()) + "."
    + ((now.getMonth() + 1 < 10) ? "0" + (now.getMonth() + 1) : (now.getMonth() + 1)) + "."
    + now.getFullYear() + " "
    + ((now.getHours() < 10) ? "0" + now.getHours() : now.getHours()) + ":"
    + ((now.getMinutes() < 10) ? "0" + now.getMinutes() : now.getMinutes());
}

// -----------------------------------------------------------------------------
// Show a given HTML element
// -----------------------------------------------------------------------------
function show(elem) {
    elem.style.display = ""; // not "block", but empty -> default browser behaviour. Problem in Firefox.
    elem.style.visibility = "visible";
}

function hide(elem) {
    elem.style.display = "none";
    elem.style.visibility = "hidden";
}

function showEx(elem, doShow) {
    if (doShow) {
        show(elem);
    } else {
        hide(elem);
    }
}
// -----------------------------------------------------------------------------
// Get top position for centered window
// -----------------------------------------------------------------------------

function getWindowTop() {
  return (top.screenLeft || top.screenTop 
    ? (top.screenTop ? top.screenTop : 0)
    : top.screenY + (top.outerHeight - top.innerHeight) - 26);
}

function getClientHeight() {
  var clientHeight = 0;
  if (top.document.documentElement && top.document.documentElement.clientHeight) {
    clientHeight = top.document.documentElement.clientHeight;
  } else if (top.document.body) {
    clientHeight = top.document.body.clientHeight;
  }
  return clientHeight;
}

function getWindowTopAsCenterOnClientArea(windowHeight) {
  var onScreenY = getWindowTop();
  var clientHeight = getClientHeight();
  var addY = ((clientHeight - windowHeight) >= 0 ? (clientHeight - windowHeight) / 2 : 0);
  var posY = (onScreenY + addY);
  return (posY > 25 ? posY - 25 : posY); // - statusbar height
}

// -----------------------------------------------------------------------------
// Get left position for centered window
// -----------------------------------------------------------------------------

function getWindowLeft() {
  return (top.screenLeft || top.screenTop 
    ? (top.screenLeft ? top.screenLeft : 0) 
    : top.screenX + (top.outerWidth - top.innerWidth) - 4);
}

function getClientWidth() {
  var clientWidth = 0;
  if (top.document.documentElement && top.document.documentElement.clientWidth) {
    clientWidth = top.document.documentElement.clientWidth;
  } else if (top.document.body) {
    clientWidth = top.document.body.clientWidth;
  }
  return clientWidth;
}

function getWindowLeftAsCenterOnClientArea(windowWidth) {
  var onScreenX = getWindowLeft();
  var clientWidth = getClientWidth();
  var addX = ((clientWidth - windowWidth) >= 0 ? (clientWidth - windowWidth) / 2 : 0);
  return (onScreenX + addX);
}



// =============================================================================

