function changeURL(urlField, queryParams){
    if (urlField.value != null && urlField.value.length>0) {
    	if (queryParams != null && queryParams.length > 0) {
    		if (queryParams.charAt(0) != '?')
    			queryParams = "?" + queryParams;
    		document.location.href = urlField.value + queryParams;
    	} else {
        document.location.href = urlField.value;
    }
}
}

function removeCmsQueryParams(query) {
	if (!query) {
		return query;
	}
	var b = query.charAt(0) == '?';
	if (!b) {
		query = "?"+query;
	}
	query = changeUrlParameter("remove", query, 'selfLocked');
	query = changeUrlParameter("remove", query, 'unitOfWork');
	query = changeUrlParameter("remove", query, 'firstCallMode');
	query = changeUrlParameter("remove", query, 'INPLACEEDITOR');
	query = changeUrlParameter("remove", query, '__anchorItem');
	query = changeUrlParameter("remove", query, '__yOffset');
	if (query.length == 1) {
		return "";
	}
	return query;
}

function changeUrlParameter(action, url, thisParam, newVal, leaveAsIs) {
      var newUrl = "";
      var ind = url.indexOf ("?");
      if (ind < 0) {
         if (action == "add") {
            newUrl = url + "?" + thisParam + "=" + escape(newVal);
         } else {
            newUrl = url;
         }
      } else {
         newUrl = url.substring (0, ind);
         var params = url.substring (ind+1, url.length);
         var paramsArray = params.split ("&");
         var paramsStr = "";
         var found = false;
         for (var i=0; i<paramsArray.length; i++) {
            if (paramsArray[i].length > 0) {
               if (paramsArray[i].indexOf (thisParam + "=") == 0) {
                  found = true;
                  if (action == "add") {
                   if (leaveAsIs) {
                      // take old parameter
                      paramsStr += ((paramsStr.length == 0)?"?":"&") + paramsArray[i];
                   } else {
                      // replace old parameter by new parameter
                      paramsStr += ((paramsStr.length == 0)?"?":"&") + thisParam + "=" + escape(newVal);
                   }
                } else {
                   // ignore parameter that is to be removed
                }
               } else {
                  // leave other parameters as they are
                  paramsStr += ((paramsStr.length == 0)?"?":"&") + paramsArray[i];
               }
            }
         }
         if (action == "add" && !found) {
            paramsStr += ((paramsStr.length == 0)?"?":"&") + thisParam + "=" + escape(newVal);
         }
         newUrl += paramsStr;
     }
     return newUrl;
}

/**********************************************/
/*        Content Functions                   */
/**********************************************/
/*        E-Mail-Form Datatype                */
/**********************************************/
var checkFormularErrorMessage = 'Please fill all mandatory form elements';
function checkFormular(elem) {
    var form = elem.form;
    var numOfElements;
    var currentElement;
    var count;

    numOfElements = form.length;
    for (count = 0; count < numOfElements; count++) {
        currentElement = form.elements[count];
        if (currentElement.getAttribute("mandatory") != null &&
            (currentElement.getAttribute("mandatory") == true ||
             currentElement.getAttribute("mandatory") == 'true')) {
            //div could be the mandatory label
            if (currentElement.tagName!='DIV') {
                if (currentElement.value == null || currentElement.value == "") {
                   alert(checkFormularErrorMessage);
                   return;
                }
            }
        }
    }

    form.submit();
}

/**********************************************/
/*        Drop-Down Box Pattern of List       */
/**********************************************/
function dropdownlinklist(elem, id) {

    var optionElem = elem.options[elem.options.selectedIndex];
    var option;
    if (optionElem == null || optionElem.value == null || optionElem.value.length == 0) {
        return;
    }

    var targetElem = document.getElementById(id+"_listform").elements["target"+elem.options.selectedIndex];
    var target = "_notarget";
    if (targetElem != null) {
        target = targetElem.value;
    }

    if (target=="_top") {
        top.location.href=optionElem.value;
    } else if (target=="_self" || target=="same") {
        self.location.href=optionElem.value;
    } else if (target=="_blank" || target=="new") {
        window.open(optionElem.value,"window"+elem.options.selectedIndex);
    } else if (target=="_parent") {
        parent.location.href=optionElem.value;
    } else { // falls target=="_notarget"
        self.location.hash = optionElem.value;
    }

}

/**********************************************/
/*        Recommendation Functions            */
/**********************************************/
function sendRecommendForm(id, url) {

  var wrapper = jQuery(id);
	var form = wrapper.find("form");
	if (wrapper && form) {
    jQuery.post(
			url,
			form.serialize() + "&_finish=Submit",
			function(html) {
				wrapper.html(html);
        }
		)
    }
    return false;
}

function getRecommendForm(id, url) {	
	
  var wrapper = jQuery(id);
	if (wrapper) {
		wrapper.show();
    jQuery.get(
			url, 
			function(html) {
				wrapper.html(html);
        },
			"html"
		);
        }
    }

/**********************************************/
/*        Authentication Functions            */
/**********************************************/

function getLayoutLoginForm(url) {
    document.location.href = url;
}

// cross domain programming using iframe
// this is because of https redirecting and the restrictions
// related to getting content of https content from http protocol
function getModuleLoginForm(url) {
    var divId = "loginDiv";
    var LoginHelper = Class.create();
    LoginHelper.prototype = {
        initialize: function() {
        },
        login: function(divId, url) {
            if (!document.getElementById(divId).hasChildNodes()) {
                var iframe = document.createElement('iframe');
                iframe.src = url;
                iframe.id = 'iframe_login';
                iframe.name = 'iframe_login';
                iframe.frameBorder = '0';
                iframe.scrolling = 'no';
                iframe.align="left";
                jQuery(divId).appendChild(iframe);
                jQuery(divId).show();
            }

        }
    }
    var loginHelper = new LoginHelper();
    loginHelper.login(divId, url);

}

// cross domain programming using iframe
// this is because of https redirecting and the restrictions
// related to getting content of https content from http protocol
function sendLoginForm(url) {
    var formName = "loginForm";
    var LoginHelper = Class.create();
    LoginHelper.prototype = {
        initialize: function() {
        },
        login: function(url) {
             new Ajax.Request(url, {
                method: 'post',
                parameters: jQuery(formName).serialize(true),
                evalScripts: true,
                onSuccess: function(transport) {
                    var params = url.parseQuery();
                    if (transport.responseText.blank()) {
                        window.top.location.href = params['url'];
                    } else {
                        document.body.innerHTML = transport.responseText;
                    }
                }
            });
        }
    }
    var loginHelper = new LoginHelper();
    loginHelper.login(url);
    return false;
}

function cancelLogin(url) {
    window.top.location.href = url;
}

/**********************************************/
/*               General Functions            */
/**********************************************/
var numbers = "0123456789";
var letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

/*
 * Check whether the field is empty
 */
function isEmpty(field) {
    if (field != null && field.length > 0) {
        return false;
    }
    return true;
}

/*
 * Check whether the field is a number
 */
function isNumber(field) {
    if (isEmpty(field)) {
        return false;
    }
    var len = field.length;
    for (i = 0; i < len; i++) {
        if (i == 0 && (field.charAt(i)=='-' || field.charAt(i)=='+')) {
           continue;
        } else if (numbers.indexOf(field.charAt(i))==-1) {
            return false;
        }
    }
    return true;
}

/*
 * Check whether the field is a valid email address
 */
function isEmail(field) {
    if (isEmpty(field)) {
        return false;
    }
    var punkt = field.indexOf(".");
    var at = field.indexOf("@");
    var lastPunkt = field.lastIndexOf(".");
    var len = field.length-1;
    if ((punkt <= 0 || punkt >= len)
        || (at <= 0 || punkt >= len)
        || (lastPunkt <= (at+1) || lastPunkt >= len)) {
        return false;
    }
    var len = field.length;
    var emailPattern=letters+numbers+"_@.-";
    for (i = 0; i < len; i++) {
        if (emailPattern.indexOf(field.charAt(i))==-1) {
            return false;
        }
    }
    return true;
}

/*
 * Check whether the fields make a valid date
 */
function isDate(fieldDay, fieldMonth, fieldYear) {
    if (!isNumber(fieldDay) || !isNumber(fieldMonth) || !isNumber(fieldYear)) {
        return false;
    }
    month = parseInt(fieldMonth,10);
    day = parseInt(fieldDay,10);
    year = parseInt(fieldYear,10);
    daysInMonth = ((month==4 || month==6 || month==9 || month==11) ? 30 : (month==2 ? (((year % 4 == 0) && ((!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28) : 31));
    if (year < 1900 || (day <= 0 || day > daysInMonth) || (month <= 0 || month > 12)) {
        return false;
    }
    return true;
}

/*
 * Build a date from valid fields for day, month and year
 */
function getDate(day, month, year) {
    return new Date(year,(month-1), day);
}

/*
 * Compares two dates together
 * Param    - smallerDate, The date that is supposed to be smaller
 * Param    - greaterDate, The date that is supposed to be greater
 */
function compareDates(smallerDate, greaterDate) {
    smallerDateTime = smallerDate.getTime();
    greaterDateTime = greaterDate.getTime();
    if (greaterDateTime < smallerDateTime) {
        return -1;
    } else if (greaterDateTime == smallerDateTime) {
      return 0;
    }
    return 1;
}

/*
 * Compares a date with current date
 */
function compareWithCurrentDate(date) {
    dateTime = date();
    currentTime = (new Date(currentYear,(currentMonth-1),currentDay)).getTime();
    if (dateTime < currentTime) {
        return false;
    }
    return true;
}

/*
 * Trim blanks from a String
 */
function trim(str) {
    return String(str).replace(/^\s+|\s+$/g,'');
}

/*
 * Checks if a String ends with a specific suffix
 */
function endsWith(full, suffix) {
  if (full==suffix) return true;
  if (!suffix) return true;
  if (!full) return false;
  if (suffix.length > full.length) return false;

  var sufIndex = full.indexOf(suffix);

  if (sufIndex == -1) return false;

  return (sufIndex == full.length-suffix.length);
}

function startsWith(field, delim) {
  var fld = field.substring(0, delim.length);
  if (fld == delim) {
    return true;
  }
  return false;
}
/*
 * check is an array contains a specific value
 */
function arrayContains(arr, elem) {
  if(!arr) return false;
  for(var i=0; i<arr.length; i++) {
    if (arr[i] == elem)
      return true;
  }
  return false;
}

function displayNonEmptyElement(elemName) {
   try {
     if (document.getElementById(elemName).innerHTML != "") {
       document.getElementById(elemName).style.display = "";
     }
   }catch(except) {}
}

/**
 * Function CMSExceptionStacktrace
 *
 * Creates an Scrollable Datagrid based on a standard table with fixed thead and tfoot
 *
 * Parameter:
 *   ex:          Exception given from try-catch
 *   msg:         Optional Error Message prefix
 *
 * Example:
 *
 *  try {
 *     alert('wrong string termination);
 *  }
 *  catch (error) {
 *     CMSExceptionStacktrace(error, 'MyErrorPrefix');
 *  }
 *  // ...
 */
function CMSExceptionStacktrace(ex, msg) {
  var str = ''
  if (msg) {
    str = msg+'\n'+'-------------------------\n';;
  }

  for (var i in ex) {
    var tmp = '(error)';
    try{ tmp = ex[i] } catch(e) {}

      str += i+': ';
      str += tmp+'\n';
  }

  alert(str);
}

/**
 * Function CMSRegisterOnloadFunction
 *
 * Registers a function for calling when page is loaded
 *
 * Parameter:
 *   functionname:       function that show be called on onload-event
 *   useCapture:         additional parameter for addEventListener call
 *
 * Example:
 *
 *  function myOnloadFunction() {
 *    alert('Hello Page!');
 *  }
 *  CMSRegisterOnloadFunction(myOnloadFunction);
 *  // ...
 */
function CMSRegisterOnloadFunction(functionname, useCapture) {
	if (window.__loaded === true) {
		functionname();
	}
	
  if ( (useCapture != null) && (useCapture == true) ) {
    useCapture = true;
  } else {
    useCapture = false;
  }

  if (!document.all) {
    window.addEventListener("load", functionname, useCapture);
  } else {
    window.attachEvent("onload", functionname);
  }
}

CMSRegisterOnloadFunction(function() {
	window.__loaded = true;
});

/**
 * Function CMSRegisterOnresizeFunction
 *
 * Registers a function for calling when page is resized
 *
 * Parameter:
 *   functionname:       function that show be called on onresize-event
 *   useCapture:         additional parameter for addEventListener call
 *
 * Example:
 *
 *  function myOnresizeFunction() {
 *    recalculateDialogElements();
 *  }
 *  CMSRegisterOnresizeFunction(myOnresizeFunction);
 *  // ...
 */
function CMSRegisterOnresizeFunction(functionname, useCapture) {
  if ( (useCapture != null) && (useCapture == true) ) {
    useCapture = true;
  } else {
    useCapture = false;
  }

  if (!document.all) {
    window.addEventListener("resize", functionname, useCapture);
  } else {
    window.attachEvent("onresize", functionname);
  }
}


/**
 * Function CMSSetWindowTitle
 *
 * Sets the title of the browser-window (document) to a new value
 *
 * Parameter:
 *   newWindowTitle:     new window-title
 *   assignToTopWindow:  assign title to top-instance of window (useful for framesets) (optional, default: false)
 *
 * Example:
 *
 *  // ...
 *  CMSSetWindowTitle('Hello WindowTitle-World!');
 *  // ...
 */
function CMSSetWindowTitle(newWindowTitle, assignToTopWindow) {
  if ( (assignToTopWindow != null) && (assignToTopWindow == true) ) {
        assignToTopWindow = true;
  } else {
    assignToTopWindow = false;
  }

  if (assignToTopWindow && window.top.document.title) {
    window.top.document.title = newWindowTitle;
  }
  else if (window.document.title) {
    window.document.title = newWindowTitle;
  }
}

/**
 * Function hasClass
 *
 * Checks an given object "el" for class "className"
 *
 * Parameter:
 *   el:            valid html-element object
 *   className:     name of class to look for
 *
 * Example:
 *
 *  var myobj = document.getElementById('myId');
 *  if (hasClass(myobj, 'myClass')) {
 *    alert('has class myClass');
 *  }
 */
function hasClass(el, className) {
        if (!(el && el.className)) {
            return;
        }
        var cls = el.className.split(" ");
        var ar = new Array();
        for (var i = cls.length; i > 0;) {
            if (cls[--i] == className) {
                return true;
            }
        }
    return false;
}


/**
 * Function addClass
 *
 * Adds class "className" to an given object
 *
 * Parameter:
 *   el:            valid html-element object
 *   className:     name of class to add
 *
 * Example:
 *
 *  var myobj = document.getElementById('myId');
 *  addClass(myobj, 'anotherClassToAdd')) {
 */
function addClass(el, className) {
        if (!(el && el.className)) {
            return;
        }
        removeClass(el, className);
        el.className += " " + className;
}

/**
 * Function removeClass
 *
 * Removes class "className" from an given object
 *
 * Parameter:
 *   el:            valid html-element object
 *   className:     name of class to remove
 *
 * Example:
 *
 *  var myobj = document.getElementById('myId');
 *  removeClass(myobj, 'classToRemove')) {
 */
function removeClass(el, className) {
        if (!(el && el.className)) {
            return;
        }
        var cls = el.className.split(" ");
        var ar = new Array();
        for (var i = cls.length; i > 0;) {
            if (cls[--i] != className) {
                    ar[ar.length] = cls[i];
            }
        }
        el.className = ar.join(" ");
}


function hasParent(elem, searchedElem) {
   var offset = 0;
   while (elem != null && ++offset < 1000) {
      elem = elem.parentNode;
      if (elem == searchedElem) {
         return true;
      }
   }
   return false;
}

function unescapeUnicode(string) {
  var str = string;
  var reg = new RegExp("%u([0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F])", "");
  var i=0;
  var arr;
  while ((arr = reg.exec(str)) != null) {
    i++;
    if(i>100000) break;
    if(arr.index >= 0) {
      str = str.substring(0, arr.index) +
      fromHex(RegExp.$1) + str.substring(arr.index+6);
    }
    else break;
  }

  return str;
}

function fromHex(str) {
  return String.fromCharCode(eval("0x"+str));
}

function refreshByEditor(id, locale, userobject) {
    var url = document.location.href;
    if (userobject != null && userobject.length > 0) {
        if (url.indexOf("?")>0) {
            url+="&";
        } else {
            url+="?";
        }
        url+="userobject="+userobject;
    }
    document.location.href=url;
}

function toggleDiv(divId) {
    var div = document.getElementById(divId);
    if (div==null) return;

    if (div.style.display == "none") {
       div.style.display = "block";
    } else if (div.style.display == "block") {
       div.style.display = "none";
    } else {
    	div.style.display = "block";
    }
}

function opwin() {
	var wstat
	var ns4up = (document.layers) ? 1 : 0
	var ie4up = (document.all) ? 1 : 0
	var xsize = screen.width
	var ysize = screen.height
	var breite=800
	var hoehe=600
	var xpos=0
	var ypos=0
    wstat=window.open("print.html","","scrollbars=yes,status=no,toolbar=no,location=no,directories=no,resizable=no,menubar=no,width="+breite+",height="+hoehe+",screenX="+xpos+",screenY="+ypos+",top="+ypos+",left="+xpos)
}

function tooltipOverlib(text) {
    overlib(text, BGCOLOR, '#7A7A7A', FGCOLOR, '#FFFFFF', CAPCOLOR, '#000000');
}

function captchaLoad(id, divid, elm) {
   if (elm.value=='') return;
   var img = document.getElementById(id);
   var div = document.getElementById(divid);
   if (img == null) {
   	  alert(id + " not found");
   	  return;
   }
   if (div == null) {
   	  alert(divid + " not found");
   	  return;
   }
   div.style.display = '';
}

function captchaReload(id) {
   var img = document.getElementById(id);
   if (img == null) {
   	  //alert for debug purpose
   	  //alert(id + " not found");
   	  return;
   }
   var src = img.src;
   if(src.indexOf('?captchaReload=')>0) {
   	  src = src.substring(0,src.indexOf('?captchaReload=')); 
   }else if(src.indexOf('&captchaReload=')>0) {
   	  src = src.substring(0,src.indexOf('&captchaReload=')); 
   }
   if(src.indexOf('?')==-1) {
   	  src += '?';
   } else {
   	  src += '&';
   }
   src += 'captchaReload=' + (new Date()).getTime();
   img.src = src;
}

function sendAndRefresh(url) {
  jQuery.post(
		url,
		null,
		function(html) {
			document.location.href = document.location.href;
		}
	)
    return false;
}

function confirmAndRefresh(url, msg) {
  jQuery.jqDialog.confirm(msg,
		function() {
      jQuery.post(
				url,
				null,
          function(html)
          {
					document.location.href = document.location.href;
				}
			)
		},
		function() {}
	);

    return false;
}

function confirmAndRedirectTo(url, msg, targetUrl, errCallback) {
  jQuery.jqDialog.confirm(msg,
		function() {
      jQuery.ajax({
				type: 'POST',
				url: url,
				success: function(html) {
					document.location.href = targetUrl;
				},
				error: errCallback
			});
		},
		function() {}
	);

    return false;
}

function confirmAndNotify(url, msg, feedback, time) {
  jQuery.jqDialog.confirm(msg,
		function() {
      jQuery.post(
				url,
				null,
				function(html) {
					if (time) {
            jQuery.jqDialog.notify(feedback, time);
					} else {
            jQuery.jqDialog.notify(feedback);
					}
					
				}
			)
		},
		function() {}
	);

    return false;
}

function createBlogEntry(locale, formid) {
  var form = jQuery('#'+formid);
	if (form == null) return;
	var localeField = form.find("input[name='locale']").first();
	localeField.attr('value', locale);
	form.submit();
}

function createForumNode(formid, quote) {
    var form = jQuery('#'+formid);
	if (form == null) return;
	try {
		var localeField = form.find("input[name='quote']").first();
		localeField.attr('value', quote);
	} catch(except){}
	form.submit();
}

