//******************* Popup global wrappers
var confirmLock = false;
var onPopupOkDefult = function () {
	// alert("onPopupOk");
};
var onPopupOk = onPopupOkDefult;
var onPopupCancelDefult = function () {
	// alert("onPopupCancel");
};
var onPopupCancel = onPopupCancelDefult;
// popup id: popupConfirm, popupMessage
/**
 * example: onclick="if(onClickWrapper(null,'id',this.onclick,[..])==false)
 * return false; cursorWait()" Why such tricky? 1. We need to pass this.onclick
 * as onOk. This is because Richfaces overrides onclick to call Ajax request in
 * the way the part we give is followed by Ajax calling code. Therefor we cannot
 * return true in onclick as well. 2. This causes more problems. onClickWrapper
 * uses jQuery as popup, then we need to provide the functions to release the
 * screen lock. onOk is the function and as we need to preserve original
 * Richfaces Ajax call this function must be onclick itself. This results in
 * onclick called two times. Second time onClickWrapper calls it as callback by
 * popup window. So we need to track which call we deal with. This is simply the
 * check if onOk is defined, if not we are sure we deal with callback, then we
 * can simply return true.
 */
var onClickWrapper = function (beforeOnClick, popupId, onOk, title, bodyText, textOk, textCancel, icon, checkBoxText) {
	if (!onOk) {
		// console.log("callbak=undefined onOk: " + onOk);
		return true;
	}
	// console.log("step 1 " + popupId + " title=" + title + " text=" + bodyText
	// + " ok:" + textOk + " cancel=" + textCancel);
	if (beforeOnClick) {
		if (!beforeOnClick()) {
			return false;
		}
	}
	// console.log("step 2 " + onOk);
	confirmLock = true;
	onPopupBtn = function () {
		// console.log("release lock");
		confirmLock = false;
		// console.log("hide popup");
		document.getElementById(popupId).component.hide();
		// console.log("release onpopupOk");
		onPopupOk = onPopupOkDefult;
		onPopupCancel = onPopupCancelDefult;
		// console.log('onPopupBtn');
	};
	onPopupCancel = function () {
		onPopupBtn();
		// console.log('cancel');
		restoreComboSelection();
	};
	onPopupOk = function () {
		onPopupBtn();
		// console.log("call onOk");
		clearComboSelection();
		onOk();
	};
	// console.log("step 3 elem=" + document.getElementById(popupId +
	// "Header"));
	document.getElementById(popupId + "Header").innerHTML = title;
	document.getElementById(popupId + "BodyText").innerHTML = bodyText;
	var okEnabled = document.getElementById(popupId + "OkEnabled");
	// console.log("okEnabled=" + okEnabled);
	if (okEnabled) {
		okEnabled.innerHTML = textOk;
	}
	if (checkBoxText) {
		// enlarge
		document.getElementById(popupId + "CDiv").style.height = "230px";
		document.getElementById(popupId + "BodyText").style.textAlign = "left";
		// show check box area
		var boxArea = document.getElementById(popupId + "CheckboxArea");
		// console.log("boxArea1=" + boxArea);
		if (boxArea) {
			boxArea.style.display = "";
			boxArea.style.visibility = "";
		}
		document.getElementById(popupId + "CheckboxText").innerHTML = checkBoxText;
		// swap ok buttons
		document.getElementById(popupId + "OkDisabled").innerHTML = textOk;
		var checkbox = document.getElementById(popupId + "Checkbox");
		// console.log("checkbox1=" + checkbox);
		if (checkbox) {
			checkbox.checked = false;
		}
		enableConfirmPopupOk(checkbox);
	} else {
		// decrease
		document.getElementById(popupId + "CDiv").style.height = "170px";
		document.getElementById(popupId + "BodyText").style.textAlign = "center";
		// hide check box area
		var boxArea = document.getElementById(popupId + "CheckboxArea");
		// console.log("boxArea2=" + boxArea);
		if (boxArea) {
			boxArea.style.display = "none";
			boxArea.style.visibility = "hidden";
		}
		// swap ok buttons
		var checkbox = document.getElementById(popupId + "Checkbox");
		// console.log("checkbox2=" + checkbox);
		if (checkbox) {
			checkbox.checked = true;
		}
		enableConfirmPopupOk(checkbox);
	}
	cancelBtn = document.getElementById(popupId + "Cancel");
	if (cancelBtn) {
		cancelBtn.innerHTML = textCancel;
	}
	document.getElementById(popupId).component.show();
	// doesn't work if in previous 'if'
	if (checkBoxText) {
		document.getElementById(popupId + "ContentDiv").style.height = "230px";
	} else {
		document.getElementById(popupId + "ContentDiv").style.height = "170px";
	}
	if (confirmLock) {
		return false;
	}
	return true;
};
function enableConfirmPopupOk(checkbox) {
	var popupLinkD = document.getElementById("confirmPopupOkDisabled");
	var popupLinkE = document.getElementById("confirmPopupOkEnabled");
	// console.log(checkbox != null);
	// console.log(popupLinkD != null);
	// console.log(popupLinkE != null);
	if (checkbox && popupLinkD && popupLinkE) {
		// console.log(checkbox.checked);
		if (checkbox.checked) {
			popupLinkD.style.display = "none";
			popupLinkE.style.display = "";
			popupLinkD.style.visibility = "hidden";
			popupLinkE.style.visibility = "";
		} else {
			popupLinkE.style.display = "none";
			popupLinkD.style.display = "";
			popupLinkE.style.visibility = "hidden";
			popupLinkD.style.visibility = "";
		}
	}
}
var confirmAction = function (callerAndCallback, title, bodyText, textOk, textCancel, textCheckBox) {
	// do not accept null, just true or false
	return onClickWrapper(null, "popupConfirm", callerAndCallback, title, bodyText, textOk, textCancel, "....warn.png", textCheckBox);
};
// ******************* Language change global warappers
/*
 * var actionComboLangChange = function (combo) { function confirmFunction() {
 * return confirmLangChangeInterceptor(combo.onchange); } return
 * interceptCombo(combo, confirmFunction); };
 */
var actionMemberTypeChange = function (combo) {
	if (needsConfirm(combo)) {
		return confirmTypeChange(combo);
	}
	combo.blur();
	clearComboSelection();
	return true;
};
/** ********** preserve combo selection ******** */
var comboId = null;
var selectedIndex = null;
function clearComboSelection() {
	comboId = null;
	selectedIndex = null;
	// console.log('clearComboSelection');
}
function storeComboSelection(combo) {
	selectedIndex = combo.selectedIndex;
	comboId = combo.id;
	// clearComboSelection();
	// console.log("storeComboSelection:" + combo + ", id :" + comboId + ",
	// selectedIndex:" + selectedIndex);
}
function restoreComboSelection() {
	if (comboId) {
		combo = document.getElementById(comboId);
		if (combo) {
		// console.log("restoreComboSelection combo:" + combo + ", id :" +
		// comboId + ", selectedIndex:" + selectedIndex);
			combo.selectedIndex = selectedIndex;
		}
	}
}
// ******** events interceptors (caller is a calling function)
// event: link onclick
function confirmLinkInterceptor(caller) {
	// accept null as true
	return confirmLinkIntercept(caller) == false ? false : true;
}
function confirmLinkIntercept(caller) {
	return true;
}
// event: cancel clicked
function confirmCancelInterceptor(caller) {
	// accept null as true
	return confirmLinkIntercept(caller) == false ? false : true;
}
function confirmCancelIntercept(caller) {
	return true;
}
// event: language combo onchange
function confirmLangChangeInterceptor(caller) {
	return confirmLangChangeIntercept(caller) == false ? false : true;
}
function confirmLangChangeIntercept(caller) {
	return true;
}
// event: confirm result - just display pop, return values just in case
function confirmResultInterceptor(caller) {
	confirmResultIntercept(caller);
}
function confirmResultIntercept(caller) {
}
function confirmTabChange(caller) {
	confirmTabChangeInterceptor(caller);
}
function confirmTabChangeInterceptor(caller) {
}
function popupWindow(title, bodyText, textOk) {
	confirmResultIntercept = function (caller) {
		onClickWrapper(null, "popupMessage", caller, title, bodyText, textOk, null, "....warn.png");
	};
	document.getElementById("popupShowResult").onclick();
	// alert(message);
}
function popupWait(title, bodyText) {
	popupId = "popupWait";
	document.getElementById(popupId + "Header").innerHTML = title;
	document.getElementById(popupId + "BodyText").innerHTML = bodyText;
	document.getElementById(popupId).component.show();
	// alert('waitTest');
}
function needsConfirm(memberTypeCombo) {
	// console.log("memberTypeCombo " + memberTypeCombo + " comboPrev=" +
	// comboPrev + " comboSelNew=" + comboSelNew);
	memberTypeCombo = document.getElementById(comboId);
	// console.log("1 " + memberTypeCombo + " ind:" + selectedIndex);
	if (memberTypeCombo) {
		prevText = memberTypeCombo.options[selectedIndex].text;
		// console.log("3 " + prevText);
		nextText = memberTypeCombo.options[memberTypeCombo.selectedIndex].text;
		// console.log("4 " + nextText);
		prevGroup = prevText.endsWith("...");
		nextIndiv = !nextText.endsWith("...");
		// console.log("prevGroup: " + prevGroup + " nextIndiv: " + nextIndiv);
		isConfirmNeeded = prevGroup && nextIndiv;
		// console.log("isConfirmNeeded " + isConfirmNeeded);
		return isConfirmNeeded;
	}
	return false;
}
var clearLoginErrors = function () {
	var table = document.getElementById("loginForm:globalErrors");
	if (table != null) {
		for (var i = 0; i < table.rows.length; i++) {
			var row = table.rows[i];
			for (var j = 0; j < row.cells.length; j++) {
				var cell = row.cells[j];
				cell.innerHTML = "";
			}
		}
	}
};

// Javascript function that will return an array of elements based on DOM
// element, tag, and class name.
// For instance, getElementsByClassName(document, 'tr', 'INFO') will get all
// "tr" tags under the document node with the "INFO" class and return an array
// of them.
function getElementsByClassName(oElm, strTagName, strClassName) {
	var arrElements = (strTagName == "*" && document.all) ? document.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for (var i = 0; i < arrElements.length; i++) {
		oElement = arrElements[i];
		if (oRegExp.test(oElement.className)) {
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements);
}
function hideRichMessages() {
	var elems = getElementsByClassName(document, "*", "rich-message");
	for (var i = 0; i < elems.length; i++) {
		elems[i].style.display = "none";
	}
	removeHighlights();
}
function clearAllErrorMessages() {
	mess = getElementsByClassName(document, "*", "error-msg");
	for (var i = 0; i < mess.length; i++) {
		chdrn = getElementsByClassName(mess[i], "*", "dynamicDivClass");
		if (chdrn.length == 0) {
			mess[i].style.display = "none";
		}
	}
	removeHighlights();
}
function removeHighlights() {
	hl = getElementsByClassName(document, "*", "error-highlight");
	for (var i = 0; i < hl.length; i++) {
		obj = hl[i];
		if (obj) {
			jscss("remove", obj, "error-highlight");
		}
	}
	return true;
}
function styleRichErrorMessages() {
	mess = getElementsByClassName(document, "*", "error-msg");
	for (var i = 0; i < mess.length; i++) {
		id = mess[i].id;
		splitted = id.split("msg-");
		if (splitted) {
			if (splitted.length == 2) {
				mess[i].style.cssText = "";
				hId = splitted[0] + splitted[1];
				applyErrStyle(hId);
			} else {
				if (splitted.length == 1) {
					splitted = id.split(":");
					if (splitted[1] && splitted[1] == "globalErrors") {
						mess[i].style.font = "12px";
					}
				}
			}
		}
	}
}
function applyErrStyle(hId) {
	obj = document.getElementById(hId);
	if (obj) {
		jscss("add", obj, "error-highlight");
	}
}
/*******************************************************************************
 * TODO: remove or fix - works sometimes function addRowFF3_old(tableId) { if
 * (!Fx3andLater) { return; } var table = document.getElementById(tableId); if
 * (table != null) { if (table.rows.length * 25 < 450) { cells = 0; if
 * (table.rows.length > 0) { cells = table.rows[0].cells.length; } row =
 * table.insertRow(table.rows.length); cell = row.insertCell(0); cell.colSpan =
 * cells; cell.style.height = "100%"; cell.style.border = "0 none"; } } }
 */
var FF3andLater = (navigator && navigator.oscpu && document.getElementsByClassName);
/*
 * to fix FF3 bug - if scrilled tablecontains less cells than needed to fill the
 * space, the heght of the rows is increased tofillthe this space the solution
 * is to add an extrarow with height="100%"
 */
function addRowFF3(tableId) {
	if (!FF3andLater) {
		return;
	}
	var tbId = tableId + ":tb";
	var tb = document.getElementById(tbId);
	// console.log("tbid: " + tableId + ", tb: " + tb + ", tb null:" + (tb ==
	// null));
	if (tb == null) {
		tbId = tableId + ":n";
		tb = document.getElementById(tbId);
	}
	// console.log("tbid: " + tableId + ", tb: " + tb + ", tb null:" + (tb ==
	// null));
	if (tb == null) {
		tbId = tableId + ":tu";
		tb = document.getElementById(tbId);
	}
	// console.log("tbid: " + tableId + ", tb: " + tb + ", tb null:" + (tb ==
	// null));
	if (tb == null) {
		tbId = tableId + ":sd";
		tb = document.getElementById(tbId);
	}
	// console.log("tbid: " + tableId + ", tb: " + tb + ", tb null:" + (tb ==
	// null));
	if (tb) {
		var trs = document.getElementsByTagName("tr");
		lastTr = trs[trs.length - 1];
		var tds = lastTr.getElementsByTagName("td");
		tr = document.createElement("tr");
    // td = document.createElement("td");
	// tr.appendChild(td);
		tb.appendChild(tr);
		var rows = tb.getElementsByTagName("tr");
		fstRow = rows[0];
		cellsCount = fstRow.cells.length;
		lastRow = rows[rows.length - 1];
		cell = lastRow.insertCell(0);
		cell.colSpan = cellsCount;
		cell.style.height = "100%";
		cell.style.border = "0 none";
	}
}
/*
 * to fix IE7 bug - if table cell content is empty then borders are not printed,
 * the solution is to add a space as content
 */
function addContentToCellsIE7(tableId) {
	if (IE7browser) {
		var tb = document.getElementById(tableId);
		if (tb) {
			var tds = tb.getElementsByTagName("td");
			for (var i = 0; i < tds.length; i++) {
				var tdEle = tds[i];
				if (tdEle.innerHTML == "") {
					tdEle.innerHTML = "&nbsp;";
				}
			}
		}
	}
}
function fixTable(tableId) {
	addRowFF3(tableId);
	// addContentToCellsIE7(tableId);
}
function cursorWait() {
	document.body.style.cursor = "wait";
}
function cursorDefault() {
	document.body.style.cursor = "default";
}
/*
 * function restoreSubmenuIE6() { obj =
 * document.getElementById("submenu_links"); obj.style.display = "none";
 * obj.style.height = "20px"; obj.style.display = "block"; fm =
 * obj.getElementsByTagName("form")[0]; inputs =
 * fm.getElementsByTagName("input"); for (var i = 0; i < inputs.length; i++) {
 * inputs[i].style.display = "none"; } }
 * 
 * function styleButtons() { if (Fx3andLater) { btns =
 * getElementsByClassName(document, "*", "memberButton"); for (var i = 0; i <
 * btns.length; i++) { btns[i].style.border='1px solid gray'; jscss("add",
 * btns[i], "memberButtonFF3"); } } }
 */
function selectAll(tbId) {
	// tbId = "addEditGroup:assigned_members_table";
	var tb = document.getElementById(tbId);
	var trs = tb.getElementsByTagName("tr");
	for (var i = 0; i < trs.length; i++) {
		var tds = trs[i].getElementsByTagName("td");
		if (tds[1]) {
			chks = tds[1].getElementsByTagName("input");
			if (chks && chks[0]) {
				chks[0].checked = true;
			}
		}
	}
}
function unselectAll(tbId) {
	// tbId = "addEditGroup:assigned_members_table";
	var tb = document.getElementById(tbId);
	var trs = tb.getElementsByTagName("tr");
	for (var i = 0; i < trs.length; i++) {
		var tds = trs[i].getElementsByTagName("td");
		if (tds[1]) {
			chks = tds[1].getElementsByTagName("input");
			if (chks && chks[0]) {
				chks[0].checked = false;
			}
		}
	}
}
function attachSelectAll(obj, tbId) {
	if (obj.checked) {
		selectAll(tbId);
	} else {
		unselectAll(tbId);
	}
}
function validateChecked(fieldId) {
	var box = document.getElementById(fieldId);
	return box.checked;
}
function submitenter(myfield, e, submitID) {
	var keycode;
	if (window.event) {
		keycode = window.event.keyCode;
	} else {
		if (e) {
			keycode = e.which;
		} else {
			return true;
		}
	}
	if (keycode == 13) {
		if (submitID == null) {
			helper = document.getElementById("enterHelper");
		} else {
			helper = document.getElementById(submitID);
		}
		clearAllErrorMessages();
		helper.click();
		return false;
	} else {
		return true;
	}
}
/*
 * //MCE helper function updateMCEContent(textAreaId) { area =
 * document.getElementById(textAreaId); if (!area) { //hack to fix id changing,
 * the id of textarea is changed to 'mce_x', where x is incerased after each
 * ajax refresh for (var i = 0; i < 100; i++) { area =
 * document.getElementById("mce_" + i); if (area) { //console.log("found area " +
 * i); break; } } } area.value =
 * tinyMCE.activeEditor.getContent({format:"raw"}); }
 */
var beforeTemplateSave = function (actionSource) {
// if (document.getElementById("messageForm:msg_msgSubject")) {
// updateMCEContent("messageForm:msg_msgBody");
// }
	clearAllErrorMessages();
	if (validate_template()) {
		cursorWait();
		document.getElementById("action_link").value = actionSource;
		return true;
	} else {
		return false;
	}
};
var beforeMessageSave = function (actionSource) {
// if (document.getElementById("messageForm:msg_msgSubject")) {
// updateMCEContent("messageForm:msg_msgBody");
// }
	clearAllErrorMessages();
	if (validate_message()) {
		cursorWait();
		document.getElementById("action_link").value = actionSource;
		return true;
	} else {
		return false;
	}
};
/* sms area */
/*
 * PURPOSE: Remove trailing blanks from our string. IN: str - the string we want
 * to RTrim
 * 
 */
function RTrim(str) {
   // We don't want to trip JUST spaces, but also tabs,
   // line feeds, etc. Add anything else you want to
   // "trim" here in Whitespace
	var whitespace = new String(" \t\n\r");
	var s = new String(str);
	if (whitespace.indexOf(s.charAt(s.length - 1)) != -1) {
      // We have a string with trailing blank(s)...
		var i = s.length - 1;       // Get length of string

      // Iterate from the far right of string until we
      // don't have any more whitespace...
		while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1) {
			i--;
		}
      // Get the substring from the front of the string to
      // where the last non-whitespace character is...
		s = s.substring(0, i + 1);
	}
	return s;
}
function isUnicodeChecked() {
	// return document.getElementById("messageForm:msg_unicode").checked ==
	// true;
	return false;
}
function smsCharCount(sms) {
	var s = new String(sms);
	var i = 0;
	var c = 0;
	var ch;
	for (i = 0; i < s.length; i++) {
		ch = s.charCodeAt(i);
		// console.log('ch:'+ch);
		// Special characters need 2-byte to transmit.
		if ((ch == 124) || (ch == 94) || (ch == 123) || (ch == 125) || (ch == 91) || (ch == 93) || (ch == 126) || (ch == 92) || (ch > 255)) {
			if (isUnicodeChecked()) {
				// If it's unicode, these special characters occupy 1 unicode
				// only
				c++;
			} else {
				c += 2;
			}
		} else {
			c++;
		}
	}
	return c;
}
function textCounter(field, countfield, numbersmsfield, fromnumber) {
	var cchMsgContent = 0;
	var sSenderId = "";
	var cchSenderId = 0;
	var fConcate = true;
	cchMsgContent = smsCharCount(RTrim(field.value));
	var lSmsLength = cchMsgContent + cchSenderId;
	if (lSmsLength > 1600) {
		var sMsgContent = field.value;
		field.value = sMsgContent.substring(0, 1600 - cchSenderId);
		alert("Sorry, your message must fit into 10 SMS.");
	} else {
		var lSingleSmsMax = 160;
		var lConcateSmsMax = 153;
		if (isUnicodeChecked()) {
			lSingleSmsMax = 70;
			lConcateSmsMax = 64;
		}
		if (lSmsLength > lSingleSmsMax) {
			if (fConcate) {
				if (lSmsLength % lConcateSmsMax > 0) {
					countfield.value = lConcateSmsMax - (lSmsLength % lConcateSmsMax);
					numbersmsfield.value = Math.floor(lSmsLength / lConcateSmsMax) + 1;
				} else {
					countfield.value = 0;
					numbersmsfield.value = Math.floor(lSmsLength / lConcateSmsMax);
				}
			} else {
				if (lSmsLength % lSingleSmsMax > 0) {
					countfield.value = lSingleSmsMax - (lSmsLength % lSingleSmsMax);
					numbersmsfield.value = Math.floor(lSmsLength / lSingleSmsMax) + 1;
				} else {
					countfield.value = 0;
					numbersmsfield.value = Math.floor(lSmsLength / lSingleSmsMax);
				}
			}
		} else {
			countfield.value = lSingleSmsMax - lSmsLength;
			numbersmsfield.value = 1;
		}
	}
}
function textCounterShort(area) {
	textCounter(area, area.form.charsLeft, area.form.smsNum, area.form.from);
}
function getUploadedName() {
	var div = document.getElementById("messageForm:upload:fileItems");
	// console.log(div);
	var tbl = div.getElementsByTagName("table")[0];
	// console.log(tbl);
	var tb = tbl.getElementsByTagName("tbody")[0];
	// console.log(tb);
	var tr = tb.getElementsByTagName("tr")[0];
	// console.log(tr);
	var td = tr.getElementsByTagName("td")[0];
	// console.log(td);
	var div1 = td.getElementsByTagName("div")[0];
	// console.log(div1);
	return div1.innerHTML;
}
function checkAttachmentName(name) {
	var tbNames = document.getElementById("messageForm:msg_attTable:tb");
	// console.log("tbNames:" + tbNames);
	if (tbNames) {
		var trs = tbNames.getElementsByTagName("tr");
		for (var i = 0; i < trs.length; i++) {
			var td = trs[i].getElementsByTagName("td")[0];
			// console.log("td:" + td);
			if (td.innerHTML == name) {
				return true;
			}
		}
	}
	return false;
}
function submitPaypalForm() {
	// console.log(document.getElementById("paypalAction"));
	var btn = document.getElementById("paypalAction");
	if (btn) {
		// alert('submiting');
		document.getElementById("paypalForm").submit();
		return;
	}
	alert("problem with the page, err 2");
}
function submitBuyCredits() {
	// console.log(document.getElementById("paypalAction"));
	var btn = document.getElementById("paypalAction");
	if (btn) {
		updatepaypalForm();
		alert("submiting");
		document.getElementById("paypalForm").submit();
		return;
	}
	alert("problem with the page, err 2");
}

// alert(checkAttachmentName(getUploadedName()));
function updatepaypalForm() {
	var creditsCount = document.getElementById("settMsgsForm:sett_msg_smsCreditsCount").value;
	var creditsTotalPrice = document.getElementById("settMsgsForm:sett_msg_smsCreditsTotal").value;
	var tb = document.getElementById("sett_msg_smsPricesTable");
	var paypalForm = document.getElementById("paypalForm");
	// console.log("paypalForm: " + paypalForm + "; tb: " + tb + ";
	// submitBuyCredits: " + creditsCount);
	if (tb && creditsCount && paypalForm && creditsTotalPrice) {
		var trs = tb.getElementsByTagName("tr");
		// console.log("trs.length: " + trs.length);
		var purchaseName = null;
		var purchasePrice = null;
		var purchaseQuantity = null;
		var td0 = null;
		var td1 = null;
		var td2 = null;
		var found = false;
		for (var i = 0; i < trs.length; i++) {
			tds = trs[i].getElementsByTagName("td");
			// console.log("tds: " + tds);
			td0 = tds[0].innerHTML;
			td1 = tds[1].innerHTML;
			td2 = tds[2].innerHTML;
			// console.log("td0:" + td0);
			// console.log("td1:" + td1);
			// console.log("td2:" + td2);
			if (td0 == creditsCount) {
				purchaseName = td2;
				purchaseQuantity = creditsCount;
				purchasePrice = creditsTotalPrice;
				found = true;
			}
		}
		// console.log("purchaseName:" + purchaseName);
		// console.log("purchaseId:" + purchaseQuantity);
		// console.log("purchasePrice:" + purchasePrice);
		// console.log("found:" + found);
		if (!found) {
			purchaseName = td2;
			purchaseQuantity = creditsCount;
			purchasePrice = creditsTotalPrice;
			found = true;
			// console.log("purchaseName:" + purchaseName);
			// console.log("purchaseId:" + purchaseQuantity);
			// console.log("purchasePrice:" + purchasePrice);
		}
		var nameField = paypalForm["item_name"];
		var quantityField = paypalForm["item_number"];
		var priceField = paypalForm["amount"];
		// console.log("priceField:" + priceField.value);
		// console.log("nameField:" + nameField.value);
		// console.log("quantityField:" + quantityField.value);
		priceField.value = purchasePrice;
		quantityField.value = purchaseQuantity;
		nameField.value = purchaseName;
		// console.log("priceField:" + priceField.value);
		// console.log("nameField:" + nameField.value);
		// console.log("quantityField:" + quantityField.value);
	} else {
		alert("problem with the page, err 1");
	}
}
Date.fromString = (function () {
	var defaults = {order:"MDY", strict:false};
	var months = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
	var abs = ["AM", "PM", "AFTERNOON", "MORNING"];
	var mark = function (str, val) {
		var lval = val.toLowerCase();
		var regex = new RegExp("^" + lval + "|(.*[^:alpha:])" + lval, "g");
		return str.replace(regex, "$1" + val);
	};
	var normalize = function (str) {
		str = str.toLowerCase();
		str = str.replace(/[^:a-z0-9]/g, "-");
		for (var i = 0; i < months.length; i++) {
			str = mark(str, months[i]);
		}
		for (var i = 0; i < abs.length; i++) {
			str = mark(str, abs[i]);
		}
		str = str.replace(/[a-z]/g, "");
		str = str.replace(/([0-9])([A-Z])/g, "$1-$2");
		str = ("-" + str + "-").replace(/-+/g, "-");
		return str;
	};
	var find_time = function (norm) {
		var obj = {date:norm, time:""};
		obj.time = norm.replace(/^.*-(\d\d?(:\d\d){1,2}(-(AM|PM))?)-.*$/, "$1");
		if (obj.time == obj.date) {
			obj.time = norm.replace(/^.*-(\d\d?-(AM|PM))-.*$/, "$1");
		}
		if (obj.time == obj.date) {
			obj.time = "";
		}
		obj.date = norm.replace(obj.time, "");
		obj.time = ("-" + obj.time + "-").replace(/-+/g, "-");
		obj.date = ("-" + obj.date + "-").replace(/-+/g, "-");
		return obj;
	};
	var find_year = function (norm) {
		var year = null;

    // Check for a 4-digit year
		year = norm.replace(/^.*-(\d\d\d\d)-.*$/, "$1");
		if (year != norm) {
			return year;
		} else {
			year = null;
		}

    // Check for a 2-digit year, over 32.
		year = norm.replace(/^.*-((3[2-9])|([4-9][0-9]))-.*$/, "$1");
		if (year != norm) {
			return year;
		} else {
			year = null;
		}

    // Check for a single 2-digit number with a leading 0
		var matches = norm.match(/-0\d-/g);
		if (matches && matches.length == 1) {
			return matches[0].substring(1, 3);
		}

    // Day is always by month, so check for explicit months in
    // first or third spot
		year = norm.replace(/^.*-[A-Z]{3}-\d\d?-(\d\d?)-.*$/, "$1");
		if (year != norm) {
			return year;
		} else {
			year = null;
		}
		year = norm.replace(/^.*-(\d\d?)-\d\d?-[A-Z]{3}-.*$/, "$1");
		if (year != norm) {
			return year;
		} else {
			year = null;
		}

    // If all else fails, use the setting for the position of the year.
		var pos = "$3";
		if (defaults.opts.order.charAt(0) == "Y") {
			pos = "$1";
		} else {
			if (defaults.opts.order.charAt(1) == "Y") {
				pos = "$2";
			}
		}
		year = norm.replace(/^.*-(\d\d?)-([A-Z]{3}|\d{1,2})-(\d\d?)-.*$/, pos);
		if (year != norm) {
			return year;
		} else {
			year = null;
		}
		return year;
	};
	var find_month = function (norm, year) {
    // Check for an explicity month
		var matches = norm.match(/[A-Z]{3}/);
		if (matches && matches.length) {
			return matches[0];
		}

    // Remove the year, and unless obviously wrong, use order
    // to chose which one to use for month.
		var parts = norm.replace(year + "-", "").split("-");
		if (parts.length != 4) {
			return null;
		}
		var order = defaults.opts.order;
		var md = order.indexOf("M") < order.indexOf("D") ? 1 : 2;
		return (parseInt(parts[md], 10) <= 12) ? parts[md] : parts[md == 1 ? 2 : 1];
	};
	var find_day = function (norm, year, month) {
		return norm.replace(year, "").replace(month, "").replace(/-/g, "");
	};
	var create_absolute = function (obj) {
		var time = obj.time.replace(/[-APM]/g, "");
		var parts = time.split(":");
		parts[1] = parts[1] || 0;
		parts[2] = parts[2] || 0;
		var ihr = parseInt(parts[0], 10);
		if (obj.time.match(/-AM-/) && ihr == 12) {
			parts[0] = 0;
		} else {
			if (obj.time.match(/-PM-/) && ihr < 12) {
				parts[0] = ihr + 12;
			}
		}
		parts[0] = ("0" + parts[0]).substring(("0" + parts[0]).length - 2);
		parts[1] = ("0" + parts[1]).substring(("0" + parts[1]).length - 2);
		parts[2] = ("0" + parts[2]).substring(("0" + parts[2]).length - 2);
		time = parts.join(":");
		var strict = defaults.opts.strict;
		if (!obj.year && !strict) {
			obj.year = (new Date()).getFullYear();
		}
		var year = parseInt(obj.year, 10);
		if (year < 100) {
			year += (year < 70 ? 2000 : 1900);
		}
		if (!obj.month && !strict) {
			obj.month = (new Date()).getMonth() + 1;
		}
		var month = String(obj.month);
		if (month.match(/[A-Z]{3}/)) {
			month = "JAN-FEB-MAR-APR-MAY-JUN-JUL-AUG-SEP-OCT-NOV-DEC-".indexOf(month) / 4 + 1;
		}
		month = ("0" + month).substring(("0" + month).length - 2);
		if (!obj.day && !strict) {
			obj.day = (new Date()).getDate();
		}
		var day = ("0" + obj.day).substring(("0" + obj.day).length - 2);
		var date = new Date();
		date.setTime(Date.parse(year + "/" + month + "/" + day + " " + time));
		return date;
	};
	var parse = function (norm) {
		return absolute(norm);
	};
	var absolute = function (norm) {
		var obj = find_time(norm);
		obj.norm = norm;
		obj.year = find_year(obj.date);
		obj.month = find_month(obj.date, obj.year);
		obj.day = find_day(obj.date, obj.year, obj.month);
		return create_absolute(obj);
	};
	return function (fuzz, opts) {
		defaults.opts = {order:defaults.order, strict:defaults.strict};
		if (opts && opts.order) {
			defaults.opts.order = opts.order;
		}
		if (opts && opts.strict != undefined) {
			defaults.opts.strict = opts.strict;
		}
		var date = parse(normalize(fuzz));
		return date;
	};
})();
function validateReportDatesRange(field) {
	// console.log("field " + field);
	var dateStr1 = document.getElementById("report_params:rep_msgFromInputDate").value;
	var dateStr2 = document.getElementById("report_params:rep_msgToInputDate").value;
	if (dateStr1 && dateStr2) {
		// console.log("dateStr1: " + dateStr1 + ", dateStr2: " + dateStr2);
		var dFrom = Date.fromString(dateStr1, {order:"YMD"});
		var dTo = Date.fromString(dateStr2, {order:"YMD"});
		// console.log("from: " + dFrom + ", to: " + dTo);
		return dFrom <= dTo;
	}
	return true;
}
/**
 * 
 * Javascript trim, ltrim, rtrim http://www.webtoolkit.info/
 * 
 */
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
function trimChars(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
function trim(str) {
	return trimChars(str, "\n\t \x00\v");
}
function trimText(fieldID) {
	var field = document.getElementById(fieldID);
	var text = field.value;
	if (text) {
		text = trim(text);
		// field.value = text;
		return text.length;
	}
	return 0;
}
function trimValue(field) {
	var text = field.value;
	if (text) {
		text = trim(text);
		field.value = text;
		return text.length;
	}
	return 0;
}
function trimValueAndLeadingZeros(field) {
	var text = field.value;
	if (text) {
		text = trim(text);
		while (text.charAt(0) == "0") {
			text = text.substring(1);
		}
		field.value = text;
		return text.length;
	}
	return 0;
}
function trimMoneyValue(field) {
	var text = field.value;
	if (text) {
		text = trim(text);
		while (text.charAt(0) == "0" && text.charAt(1) && text.charAt(1) != ".") {
			// alert("1");
			text = text.substring(1);
		}
		var first = text.indexOf(".");
		var last = text.lastIndexOf(".");
		if (first >= 0 && last >= 0 && first != last) {
			// alert("2: " + text + " " + first + " " + last);
			text = text.substring(0, last);
		}
		if (first >= 0 && text.length > first + 3) {
			// alert("3: " + text + " " + first + " " + last);
			text = text.substring(0, first + 3);
		}
		field.value = text;
		return text.length;
	}
	return 0;
}
function numbersonly(e, decimal) {
	var key;
	var keychar;
	if (window.event) {
		key = window.event.keyCode;
	} else {
		if (e) {
			key = e.which;
		} else {
			return true;
		}
	}
	keychar = String.fromCharCode(key);
	if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13) || (key == 27)) {
		return true;
	} else {
		if ((("0123456789").indexOf(keychar) > -1)) {
			return true;
		} else {
			if (decimal && (keychar == ".")) {
				return true;
			} else {
				return false;
			}
		}
	}
}
function redirectJsOk(url) {
	// alert('redirect');
	window.location = url;
}
function setupTimeZone() {
	var rightNow = new Date();
	var date1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);
	var date2 = new Date(rightNow.getFullYear(), 6, 1, 0, 0, 0, 0);
	var temp = date1.toGMTString();
	var date3 = new Date(temp.substring(0, temp.lastIndexOf(" ") - 1));
	var temp = date2.toGMTString();
	var date4 = new Date(temp.substring(0, temp.lastIndexOf(" ") - 1));
	var hoursDiffStdTime = (date1 - date3) / (1000 * 60 * 60);
	var hoursDiffDaylightTime = (date2 - date4) / (1000 * 60 * 60);
	var dstObserved = false;
	if (hoursDiffDaylightTime == hoursDiffStdTime) {
				      // alert("Time zone is GMT " + hoursDiffStdTime +
						// ".nDaylight Saving Time is NOT observed here.");
	} else {
				      // alert("Time zone is GMT " + hoursDiffStdTime +
						// ".nDaylight Saving Time is observed here.");
		dstObserved = true;
	}
	document.getElementById("dstObserved").value = dstObserved;
	document.getElementById("timeOffSet").value = hoursDiffStdTime;
}
function insertAtCursor(myField, myValue) {
	if (document.selection) {
	// IE
		myField.focus();
		sel = document.selection.createRange();
		sel.text = myValue;
	} else {
	// MOZILLA
		if (myField.selectionStart || myField.selectionStart == "0") {
			var startPos = myField.selectionStart;
			var endPos = myField.selectionEnd;
			myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
		} else {
			myField.value += myValue;
		}
	}
}
function validateEventNotifTemplates(validatedId) {
	// forIds="event_add_notifTemplEmail,event_edit_notifTemplEmail,event_add_notifTemplSms,event_edit_notifTemplSms"
	// />
	var templ1 = document.getElementById("tabbedFormEdit:event_edit_notifTemplEmail");
	var templ2 = document.getElementById("tabbedFormEdit:event_edit_notifTemplSms");
	if (templ1 == null) {
		templ1 = document.getElementById("tabbedFormAdd:event_add_notifTemplEmail");
		templ2 = document.getElementById("tabbedFormAdd:event_add_notifTemplSms");
	}
	// console.log("templ1:" + templ1 + ", templ2:" + templ2);
	var selected1 = templ1.options[templ1.selectedIndex].value;
	var selected2 = templ2.options[templ2.selectedIndex].value;
	// console.log("selected1:" + selected1 + ", selected2:" + selected2);
	var templ1Ok = selected1 != "__UNASSIGNED";
	var templ2Ok = selected2 != "__UNASSIGNED";
	// console.log("templ1Ok:" + templ1Ok + ", templ2Ok:" + templ2Ok);
	return templ1Ok || templ2Ok;
}
function hasClass(ele, cls) {
	return ele.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
}
function addClass(ele, cls) {
	if (!this.hasClass(ele, cls)) {
		ele.className += " " + cls;
	}
}
function removeClass(ele, cls) {
	if (hasClass(ele, cls)) {
		var reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
		ele.className = ele.className.replace(reg, " ");
	}
}
function enableConfirmPopupLinkOk(checkbox) {
	var popupLinkD = document.getElementById("confirmPopupLinkOkDisabled");
	var popupLinkE = document.getElementById("confirmPopupLinkOkEnabled");
	// console.log(checkbox != null);
	// console.log(popupLinkD != null);
	// console.log(popupLinkE != null);
	if (checkbox && popupLinkD && popupLinkE) {
		// console.log(checkbox.checked);
		if (checkbox.checked) {
			// popupLinkD.style.display = "none";
			// popupLinkE.style.display = "";
			popupLinkD.style.visibility = "hidden";
			popupLinkE.style.visibility = "";
		} else {
			// popupLinkE.style.display = "none";
			// popupLinkD.style.display = "";
			popupLinkE.style.visibility = "hidden";
			popupLinkD.style.visibility = "";
		}
	}
}

/*
 * function eventFutureToPast(startDate) { if(startDate) { var now = } }
 */