// ===========================================================================
// Purpose: library of functions used in user pages
//
// $Id: public.js,v 1.1 2006/01/20 10:06:33 rz Exp $

//------------------------------------------------------------------------------------
// Get parameter with given name from 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);
}

//------------------------------------------------------------------------------
// trim the spaces enclosed the core of text
//------------------------------------------------------------------------------

function trim(value) {
	if (!value || (value == null))
		return "";
	if (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);
}

//------------------------------------------------------------------------------------
// 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;
}

//------------------------------------------------------------------------------------
// Check form in Contact element
//------------------------------------------------------------------------------------

function checkContactForm(form) {

  // check name
  form.f_visitor_name.value = trim(form.f_visitor_name.value);
  if (form.f_visitor_name.value.length == 0) {
    alert(res["contact.error.missing.field.name"]);
    form.f_visitor_name.focus();
    return false;
  }

  // check contact - email or tel or fax or address
  form.f_visitor_email.value = trim(form.f_visitor_email.value);
  form.f_visitor_tel.value = trim(form.f_visitor_tel.value);
  form.f_visitor_fax.value = trim(form.f_visitor_fax.value);
  form.f_visitor_address.value = trim(form.f_visitor_address.value);
  if ((form.f_visitor_email.value.length == 0) &&  (form.f_visitor_tel.value.length == 0) &&
      (form.f_visitor_fax.value.length == 0) && (form.f_visitor_address.value.length == 0)) {
    alert(res["contact.error.missing.contact.fields"]);
    form.f_visitor_email.focus();
    return false;
  }

	// check email if not empty
	if (form.f_visitor_email.value.length > 0) {
	  if (!checkEmailAddress(form.f_visitor_email.value)) {
      alert(res["contact.error.invalid.email"]);
      form.f_visitor_email.focus();
      return false;
		}
	}

	// check text
  form.f_visitor_text.value = trim(form.f_visitor_text.value);
	if (form.f_visitor_text.value.length == 0) {
      alert(res["contact.error.missing.field.text"]);
      form.f_visitor_text.focus();
      return false;
	}

	return true;
}


//------------------------------------------------------------------------------------
// Submit form in Contact element
//------------------------------------------------------------------------------------
function submitContactForm(form) {
  if (!checkContactForm(form)) {
    return;
  }
  form.f_action.value = 'send_submit';
  form_contact.submit();
}

//------------------------------------------------------------------------------
// 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)) {
            stopNoDoubleClick(true);
            return false;
        }

        eval("document." + form.name + "." + actionParamName + ".value = '" + action + "'");
        if (trim(idParamName) != '') {
            eval("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 {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;
}

//------------------------------------------------------------------------------
// Check form parameter for HtDig search
//------------------------------------------------------------------------------

function checkSubmitSucheForm(form, errmsgMisingWords) {
	// check "words" parameter
	if (form.f_words_and.value.length > 0) {
		form.f_search_words.value = form.f_words_and.value;
		form.f_search_method.value = "and";
	} else {
		if (form.f_words_or.value.length > 0) {
			form.f_search_words.value = form.f_words_or.value;
			form.f_search_method.value = "or";
		} else {
			alert((errmsgMisingWords) ? errmsgMisingWords : "Wort fehlt");
			form.f_words_and.focus();
			return false;
		}
	}
	// check "date" parameter
	if (form.f_date) {
    var selectedDate = form.f_date[(form.f_date.selectedIndex >= 0) ? form.f_date.selectedIndex : 0].text;
  	if (selectedDate == "seit gestern") {
  		form.f_search_endday.value = "-1";
  	} else if (selectedDate == "in der letzten Woche") {
  		form.f_search_endday.value = "-7";
  	} else if (selectedDate == "im letzten Monat") {
  		form.f_search_endmonth.value = "-1";
  	} else if (selectedDate == "im letzten Jahr") {
  		form.f_search_endyear.value = "-1";
  	}
  }

	// check "matchesperpage"
	var selectedMatches = form.f_nrresults[(form.f_nrresults.selectedIndex >= 0) ? form.f_nrresults.selectedIndex : 0].text;
	// -- number is first, separated with space
	selectedMatches = selectedMatches.substring(0, selectedMatches.indexOf(" "));
	form.f_search_matchesperpage.value = selectedMatches;

	return true;
}

//------------------------------------------------------------------------------
// Call HtDig search page with parameters
//------------------------------------------------------------------------------

function doHtDigSearch(searchPageUrl, restrictTo, form) {
	if (!form.f_search_text.value)
		form.f_search_text.value = "";
		
	lnk = searchPageUrl + "?f_action=search&f_search_words=" + escape(form.f_search_text.value)
    + ((restrictTo != "") ? "&f_search_restrict=" + restrictTo : "");
	window.location.href = lnk;
	return false;
}

//------------------------------------------------------------------------------
// Open AssetManagement window as popup.
// @param smPagesFolder site man. 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

function callAm(smPagesFolder, assetType, assetId, callbackId) {
	var win, viewParams, initParams, winName, leftPosition, winHeight;

	initParams = 'f_opener_type=admin&f_asset_type=' + assetType;
	viewParams = ( ((trim(assetId) != "") && (eval(assetId) > 0)) ? "&f_action=view&f_asset_id=" + assetId : "&f_action=list" );
	viewParams += ( (trim(callbackId) != "") ? "&f_callback_id=" + trim(callbackId) : "");
	winName = 'am_admin';
	leftPosition = screen.width - 539;
	winHeight = ( (screen.width >= 800) ? 700 : 550 );

	win = window.open(smPagesFolder + 'am.html?' + initParams + viewParams, winName,
		'width=519, height=' + winHeight + ', top=10, left=' + leftPosition + ', scrollbars=no, menubar=no');

	win.opener = self;
	win.focus();
}

function callAMFromPage(smPagesFolder, assetType, assetId, callbackId, pageUrl) {
	var win, viewParams, initParams, winName, leftPosition, winHeight;

	initParams = 'f_opener_type=page&f_page_url=' + pageUrl + '&f_asset_type=' + assetType;
	viewParams = ( ((trim(assetId) != "") && (eval(assetId) > 0)) ? "&f_action=view&f_asset_id=" + assetId : "&f_action=list" );
	viewParams += ( (trim(callbackId) != "") ? "&f_callback_id=" + trim(callbackId) : "");
	winName = 'am_admin';
	leftPosition = screen.width - 539;
	winHeight = ( (screen.width >= 800) ? 700 : 550 );

	win = window.open(smPagesFolder + 'am.html?' + initParams + viewParams, winName,
		'width=519, height=' + winHeight + ', top=10, left=' + leftPosition + ', scrollbars=no, menubar=no');

	win.opener = self;
	win.focus();
}

//------------------------------------------------------------------------------
// Open category selection window
//------------------------------------------------------------------------------

function callSelectCategoryWindow(smPagesFolder, mySiteId, contentType, callbackId, selectedCategories) {
	if (!selectedCategories || (trim(selectedCategories) == "all")) {
		selectedCategories = "";
	}

	var win = window.open(smPagesFolder + "public/select_categories.html?f_mysite_id=" + mySiteId
			+ "&f_content_type=" + contentType + "&f_callback_id=" + callbackId
			+ "&f_selected_categories=" + selectedCategories,
		"PublicSelectCategories", "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();
	}
}

//------------------------------------------------------------------------------
// Call Direct Configuration Popup for page with specified path
//------------------------------------------------------------------------------

function callDirectConfig(page) {
	var winLeft = (screen.width - 552) / 2;
	var winHeight = ( (screen.width > 800) ? 700 : 560 );

	var win = window.open(context.sp + context.dspagesfolder + "config/pageconfig.html?f_page_url=" + page, 
		"DirectConfig", "width=542, height=" + winHeight + ", top=5, left=" + winLeft + ", scrollbars=yes, menubar=no");
  if (win != null) {
  	win.opener = self;
    win.focus();
  }
}

// callback from
function callbackDirectConfig() {
    document.location.href=document.location;
}

//------------------------------------------------------------------------------
// Functions for DirectEdit and DirectConfig support
//------------------------------------------------------------------------------

function activate(id) {
    var el = document.getElementById(id);
    if (el.className == "editarea_norm") {
        el.className = "editarea_over";
    }
}

function deactivate(id) {
    var el = document.getElementById(id);
    if (el.className == "editarea_over") {
        el.className = "editarea_norm";         
    }
}

//------------------------------------------------------------------------------------
// 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)
		return "";
	if (sourceString.length == 0)
		return sourceString;
	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;
}

//------------------------------------------------------------------------------
// 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();
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);
  }
}

// stop timer checking double click
function stopNoDoubleClick(callEvent) {
  if (dsDoubleClickTimerRunning) {
    clearInterval(dsDoubleClickTimerID);
    dsDoubleClickTimerRunning = false;
  }

  if (callEvent && window.onStopNoDoubleClick) {
    window.onStopNoDoubleClick();
  }
}

//------------------------------------------------------------------------------------
// News gallery
//------------------------------------------------------------------------------------
function callNewsGalleryWindow(galID) {
    var winLeft = (screen.availWidth - 660) / 2;
    var winTop = (screen.availHeight - 600) / 2;
	win = window.open(context.sp + context.pagesfolder + "news_gallery.html?f_newsitem_id=" + galID, "newsgallery",
		"width=660, height=600, top=" + winTop + ", left=" + winLeft + ", scrollbars=no, menubar=no");
	win.opener = self;
	win.focus();
}

//------------------------------------------------------------------------------------
// Events gallery
//------------------------------------------------------------------------------------
function callEventGalleryWindow(galID) {
    var winLeft = (screen.availWidth - 660) / 2;
    var winTop = (screen.availHeight - 600) / 2;
	win = window.open(context.sp + context.pagesfolder + "events_gallery.html?f_event_id=" + galID, "eventgallery",
		"width=660, height=600, top=" + winTop + ", left=" + winLeft + ", scrollbars=no, menubar=no");
	win.opener = self;
	win.focus();
}

//------------------------------------------------------------------------------------
// AdBanner click popup window
//------------------------------------------------------------------------------------

function callBannerAdWindow(bannerId, mySiteId) {
  var win = window.open(context.sp + context.dspagesfolder + "public/adclick.html?id=" 
      + bannerId + "&f_mysite_id=" + mySiteId, "BannerAdWindowPopup");
  
  if (win != null) {
    win.opener = self;
    win.focus();
  }
  return false;
}

// -----------------------------------------------------------------------------
// 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;
}

//------------------------------------------------------------------------------
// Call Direct Title Popup for page with specified path
//------------------------------------------------------------------------------

function PageTitle_toString() {
	return "[{headline=" + this.headline + "}{title=" + this.title + "}{subtitle=" + this.subtitle +
	       "}{teaser=" + this.teaser + "}]";
}

function PageTitle() {
	this.headline = null;
	this.title = null;
	this.subtitle = null;
	this.teaser = null;

	this.toString = PageTitle_toString;
} 

function getPageTitle(form) {
    var pageTitle = new PageTitle();

    var obj = form.elements["pageTitle_headline"];
    pageTitle.headline = (obj ? obj.value : "");
    
    obj = form.elements["pageTitle_title"];
    pageTitle.title = (obj ? obj.value : "");

    obj = form.elements["pageTitle_subtitle"];
    pageTitle.subtitle = (obj != null ? obj.value : "");

    obj = form.elements["pageTitle_teaser"];
    pageTitle.teaser = (obj != null ? obj.value : "");

    return pageTitle;
}

function callDirectTitle(page, title) {
	var win = window.open(context.sp + context.dspagesfolder + "public/page_directtitle.html?f_init=1&f_page_url=" + page, 
		"DirectFile", "width=650, height=560, top=10, left=" + ((screen.width - 650) / 2) + ", scrollbars=yes, menubar=no");
	win.opener = self;
	win.focus();
}

// callback from DirectTitle popup
function callbackDirectTitle(pageTitle) {
  var obj = document.getElementById("pageTitle_headline");
  if (obj) {
    obj.innerHTML = (pageTitle.headline != null ? pageTitle.headline : "");
  }
  obj = document.getElementById("pageTitle_title");
  if (obj) {
    obj.innerHTML = (pageTitle.title != null ? pageTitle.title : "");
  }
  obj = document.getElementById("pageTitle_subtitle");
  if (obj) {
    obj.innerHTML = (pageTitle.subtitle != null ? pageTitle.subtitle : "");
  }
  obj = document.getElementById("pageTitle_teaser");
  if (obj) {
    obj.innerHTML = (pageTitle.teaser != null ? pageTitle.teaser : "");
  }

  //document.location.href=document.location;
}

//------------------------------------------------------------------------------
// Call Direct Image Popup for page with specified path
//------------------------------------------------------------------------------

function callDirectImage(page, areaName, useHint) {
	var win = window.open(context.sp + context.dspagesfolder + "public/page_directimage.html" 
      + "?f_init=1&f_use_hint=" + useHint + "&f_page_url=" + page + "&f_page_area_name=" + areaName, 
		"DirectImage", "width=650, height=560, top=10, left=" + ((screen.width - 650) / 2) + ", scrollbars=yes, menubar=no");
	win.opener = self;
	win.focus();
}

// callback from DirectImage popup
function callbackDirectImage(areaName) {
    document.location.href=document.location;
}

//------------------------------------------------------------------------------
// Call Direct File Popup for page with specified path
//------------------------------------------------------------------------------

function callDirectFile(page, areaName) {
	var win = window.open(context.sp + context.dspagesfolder + "public/page_directfile.html" 
      + "?f_init=1&f_use_hint=0&f_page_url=" + page + "&f_page_area_name=" + areaName, 
		"DirectFile", "width=650, height=560, top=10, left=" + ((screen.width - 650) / 2) + ", scrollbars=yes, menubar=no");
	win.opener = self;
	win.focus();
}

// callback from DirectFile popup
function callbackDirectFile(areaName) {
    document.location.href=document.location;
}

//------------------------------------------------------------------------------
// Call Editor in Popup for page with specified path
//------------------------------------------------------------------------------

function callDirectEdit(page, bodyName, contentWidth) {
  var winWidth = (screen.width - 100);
  contentWidth = trim(contentWidth);
  if (contentWidth == "" || contentWidth.indexOf("%") >= 0) {
    // standard width
    
  } else if (contentWidth.indexOf("px") >= 0) {
    var myWidth = new Number(contentWidth.substring(0, contentWidth.length() - 2).trim());
    winWidth = (isNaN(myWidth) ? winWidth : myWidth + 50);
    
  } else {
    var myWidth = new Number(contentWidth);
    winWidth = (isNaN(myWidth) ? winWidth : myWidth + 50);
  }
  if (winWidth < 720) {
    winWidth = 720;
  }
  var win = window.open(context.sp + "/system/workplace/jsp/editors/editor.html?resource=" + page
      + "&directedit=true&bodylanguage=de&bodyname=" + bodyName + "&closeonexit=true&backlink=" + page,
    "Editor" + ("" + Math.random()).substring(2), 
    "width=" + winWidth + ", height=" + (screen.height - 100) + ", top=10, left=80, scrollbars=yes, menubar=no, resizable=yes");
  if (win) {
    win.opener = top;
    win.focus();
  }
}

// callback from editor popup
function callbackDirectEdit(bodyName, bodyContent) {
  var obj = document.getElementById("pageBody_" + bodyName);
  if (obj) {
    obj.innerHTML = trim(bodyContent);
  }
}

//------------------------------------------------------------------------------