
/**
 * no prototype framework, because not all pages has it.
 * if you try to deliver XML without CDATA, you should avoid special characters within it like '&',
 * because this will not works: 'xmlResponse.firstChild..getElementsByTagName('paging')' cause parse error.
 */

// Loads XML for a given url and passes it on to the processReqChange function
function xmlLoader(url){
	req = false;
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	// JScript gives us Conditional compilation, we can cope with old IE versions.
	// and security blocked creation of the objects.
	try {
		req = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			req = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (E) {
			req = false;
		}
	}
	@end @*/
	if (!req && typeof XMLHttpRequest != 'undefined') {
		try {
			req = new XMLHttpRequest();
		} catch (e) {
			req = false;
		}
	}
	if (!req && window.createRequest) {
		try {
			req = window.createRequest();
		} catch (e) {
			req = false;
		}
	}
	
	if (!req) return false;
	req.open("GET", url, false);
	req.send(null);
 	return req.responseXML;
}

function renderUsersUnreadThreadsNotification(ajaxRequestUrl, htmlElementNameRenderInto) {
	ajaxRequestUrl += '&action=commMsg&func=unreadThreadNumber';
	var xmlResponse = xmlLoader(ajaxRequestUrl);
	try {
		var responseCode = xmlResponse.firstChild.getAttribute("code");
		var htmlToAppend = xmlResponse.firstChild.firstChild.nodeValue;
		// only display the number, if everything is ok
		if(responseCode == 0) {
			document.getElementById(htmlElementNameRenderInto).innerHTML = htmlToAppend;
		}
	}
	catch(exc) {
		// ignore
	}	
}

/* UserData */
function renderUserData(loadedMessage, userData) {
	loadedMessage = loadedMessage.replace(/\$_username/, userData.getUsername());
	loadedMessage = loadedMessage.replace(/\$_nickname/, userData.getNickname());
	loadedMessage = loadedMessage.replace(/\$_rankingpoints/, userData.getRankingpoints());
	loadedMessage = loadedMessage.replace(/\$_rankingicon/, '<img alt="' + userData.getImagealt() + '" src="' + userData.getImagesource() + '" class="user_ranking"/>');
	
	var hdrWelcome = document.getElementById('hdrWelcome');
	hdrWelcome.innerHTML = loadedMessage;
}

function getUserData(url) {
	url = url + "&sid=" + Math.random()
	
	if (!xmlLoader) return;
	var xmlUserDataReq = xmlLoader(url);
	
	if(xmlUserDataReq) {
		var userData = new UserData();
		userData.setUsername(getValueOf(xmlUserDataReq, "username"));
		userData.setNickname(getValueOf(xmlUserDataReq, "nickname"));
		userData.setRankingpoints(getValueOf(xmlUserDataReq, "rankingpoints"));
		userData.setRankingtitle(getValueOf(xmlUserDataReq, "rankingtitle"));
		userData.setImagesource(getValueOf(xmlUserDataReq, "imagesrc"));
		userData.setImagealt(getValueOf(xmlUserDataReq, "imagealt"));
		return userData;
	}
	return null;
}

function getValueOf(xmlUserDataReq, elemName) {
	if (xmlUserDataReq.getElementsByTagName(elemName)[0] && xmlUserDataReq.getElementsByTagName(elemName)[0].length != 0) {
		return xmlUserDataReq.getElementsByTagName(elemName)[0].childNodes[0].nodeValue;
	}
	return null;
}

function UserData() {
	this.username;
	this.nickname;
	this.rankingpoints;
	this.rankingtitle;
	this.imagesource;
	this.imagealt;
}

UserData.prototype.setUsername = function(value) {
	this.username = value;
}

UserData.prototype.getUsername = function() {
	return this.username;
}

UserData.prototype.setNickname = function(value) {
	this.nickname = value;
}

UserData.prototype.getNickname = function() {
	return this.nickname;
}

UserData.prototype.setRankingpoints = function(value) {
	this.rankingpoints = value;
}

UserData.prototype.getRankingpoints = function() {
	return this.rankingpoints;
}

UserData.prototype.setRankingtitle = function(value) {
	this.rankingtitle = value;
}

UserData.prototype.getRankingtitle = function() {
	return this.rankingtitle;
}

UserData.prototype.setImagesource = function(value) {
	this.imagesource = value;
}

UserData.prototype.getImagesource = function() {
	return this.imagesource;
}

UserData.prototype.setImagealt = function(value) {
	this.imagealt = value;
}

UserData.prototype.getImagealt = function() {
	return this.imagealt;
}
/* End of UserData */

// search popup box
function focusSearchfield(defaultValue) {
	var searchField = document.getElementById('searchfield');
	if (searchField && searchField.value == defaultValue) searchField.value = '';
}

function blurSearchfield(defaultValue) {
	var searchField = document.getElementById('searchfield');
	if (searchField && searchField.value == '') searchField.value = defaultValue;
}

//handle focus and blur for input fields
function focusInputField(elem, value, isPassword) {
	var inputField = typeof(elem) == 'object' ? elem : document.getElementById(elem);
	if (inputField && inputField.value == value)
		inputField.value = '';
}

function blurInputField(elem, value, isPassword) {
	var inputField = typeof(elem) == 'object' ? elem : document.getElementById(elem);
	if (inputField && inputField.value == '')
		inputField.value = value;
}

//display/hide html elements
function htmlElementToggle(elemId)
{
	 var e=document.getElementById(elemId);
	 if (!e) return;
	 
	 if(e.style.display=='none'){
	   e.style.display='block';
	 } else {
	   e.style.display='none';
	 }
}

function htmlElementOpen(elemId) {
  var e = document.getElementById(elemId);
  if (!e) return;
  e.style.display = 'block';
}

function htmlElementClose(elemId) {
  var e = document.getElementById(elemId);
  if (!e) return;
  e.style.display = 'none';
}



// ajax login popup

/* Executes functions after Ajax-Login:
 * - If the user is loggedin (isLoggedIn='true'), the parameter callback (must be a function) is executed.
 * - If the user is not logged in, the Login-Ajax-Layer is shown. After a successful login, the parameter callbackAfterLogin (must be a function) is executed.*/
function executeActionAfterLogin(siteId, locale, isLoggedIn, callback, callbackAfterLogin) {
	if (isLoggedIn=='true') {
		callback();
	} else {
		var layerId = 'loginPopupForAjaxActions';

		//hide former error messages
		hideAjaxLoginError(layerId);
		// create layer
		layerObj = new Layer(layerId, '400', '200', 1, 1, 1, 1, '', '', '', 'false', '', '');
		// form event
		$(layerId).select('form[id="loginForm"]').each(function(formItem){
			Event.stopObserving(formItem, 'submit');
			formItem.observe('submit', function(event) {
				event.preventDefault();
				var url = 'servlet/AjaxActionServlet?';
				url += 'siteid='+siteId;
				url += '&locale='+locale;
				url += '&action=login';
				url += '&uname='+encodeURIComponent($F(Element.select(formItem,'[id="login"]')[0]));
				url += '&pass='+encodeURIComponent($F(Element.select(formItem,'[id="password"]')[0]));
				new Ajax.Request(url, {
					method: 'post',
					// show spinner
					onLoading: function() {
						Element.hide($(layerId));
						showAjaxWaitingScreenWithDim('loginPopupForAjaxActions_waiting', $(layerId));
					},
					// hide spinner
					onComplete: function() {
						hideAjaxWaitingScreen('loginPopupForAjaxActions_waiting');
					},
					onSuccess: function(response) {
						var code = getAjaxResponseReturncode(response);
						// success: trigger callback
						if (code == '0') {
							layerObj.HideLayer();
							callbackAfterLogin();
						// error: 
						} else {
							Element.show($(layerId));
							showAjaxLoginError(layerId, code);
						}
					}
				});
			});
		});
		// close-btn event
		$(layerId).select('.closeLayerBtn').each(function(item){
			Event.stopObserving(item, 'click');
			item.observe('click', function(event) {
				layerObj.HideLayer();
			});
		});
		layerObj.ShowLayer();
	}
}

function hideAjaxLoginError(layerId) {
	var errorsDiv = Element.select($(layerId), '.errors')[0];
	Element.hide(errorsDiv);
}
function showAjaxLoginError(layerId, code) {
	var errorsDiv = Element.select($(layerId), '.errors')[0];
	Element.select(errorsDiv, '.error').each(function(item){
		var divCode = '';
		Element.classNames(item).each(function(className) {
			if (className.indexOf('error_')==0) {
				divCode = className.substring('error_'.length, className.length);
			}
		});
		if (code == divCode) {
			Element.show(item);
		} else {
			Element.hide(item);
		}
	});
	Element.show(errorsDiv);
}

function getAjaxResponseReturncode(response) {
	var xmlDoc = response.responseXML;
	if(xmlDoc) {
		var elem = xmlDoc.firstChild;
		if(elem) {
			var code = elem.getAttribute("code");
			return code;
		}
	}
	return null;
}

function createElement(type, id, classnames) {
	var e = document.createElement(type);
	Element.extend(e);
	if(id) { e.id = id; }
	if(classnames) { e.addClassName(classnames); }
	return e;
}


/*
 *   
 * Show message in simple layer.
 * IMPORTANT: Make sure that integratedLayser.js is included.
 * 
 * */
function simpleAlert(alertText,buttonText,boxWidth, boxHeight){	
	var defaultText = 'An error occured. Please try again later.';
	if(!alertText) {
		alertText = defaultText;
	}
	
	if(!boxWidth) { var boxWidth = '400px'; }
	if(!boxHeight) { var boxHeight = '250px'; }
	
	var lyr = createElement('div', 'lyr_simpleAlertBoxLayerWrapper', null);
	var lyrDivBG = createElement('div', 'lyr_simpleAlertBoxLayer_lightbox', 'lyr_simpleAlertBox lightbox_class');
	var lyrDivBox = createElement('div', 'lyr_simpleAlertBoxLayer', 'layer_instance');
	lyrDivBox.setStyle({
		position: 'absolute',
		display: 'none',
		width: boxWidth,
		height: boxHeight,
		zIndex: '20000'
		});

	// div#addToMyRecipeBoxWrapper
	var content = createElement('div', 'lyr_simpleAlertBoxLayer_content', null);
	Element.update(content, alertText);
	
	var btnOk = document.createElement('button');
	btnOk.innerHTML = buttonText;

	Element.insert(lyrDivBox, content);
	Element.insert(lyrDivBox, btnOk);
	Element.insert(lyr, lyrDivBG);
	Element.insert(lyr, lyrDivBox);

	$('pageBody').insert ({'bottom':lyr});
	
	var layerId = 'lyr_simpleAlertBoxLayer';
	var lyrWidth = boxWidth;
	var lyrHeight= boxHeight;
	var startX = 1;
	var startY = 1;
	var endX = 1;
	var endY = 1;
	var lyrSpeed = '';
	var easeFactor = ''; 
	var lyrDelay = '';
	var lyrDisplay = 'false';
	var foTime = '';
	var foPath = '';

	var layer_simpleAlertBoxLayer = new Layer(layerId, lyrWidth, lyrHeight, startX, startY, endX, endY, lyrSpeed, easeFactor, lyrDelay, lyrDisplay, foTime, foPath);
	layer_simpleAlertBoxLayer.ShowLayer();

	lyrDivBG.setStyle({
		height: document.compatMode=="CSS1Compat" ? Math.max(document.documentElement.clientHeight, document.body.offsetHeight)+"px" : body.clientHeight+"px"
	});

	Event.observe(btnOk, 'click', function(event) {
		layer_simpleAlertBoxLayer.HideLayer();
	});

}

/**
 * see XSL template SimpleModalDialog and related functions showSimpleModalWaitingDialog, 
 * hideSimpleModalWaitingDialog, showSimpleModalSuccessDialog, showSimpleModalErrorDialog.
 * @param actionHandler function for OK button.
 */
function showSimpleModalDialog(htmlDialogElementId, actionHandler) {
	if(!$(htmlDialogElementId)) return; // is requested dialog rendered ?
	var lyrWidth = '400';
	var lyrHeight= '250';
	var startX = 1;
	var startY = 1;
	var endX = 1;
	var endY = 1;
	var lyrSpeed = '';
	var easeFactor = ''; 
	var lyrDelay = '';
	var lyrDisplay = 'false';
	var foTime = '';
	var foPath = '';

	// create dialog
	layerObj = new Layer(htmlDialogElementId, lyrWidth, lyrHeight, startX, startY, endX, endY, lyrSpeed, easeFactor, lyrDelay, lyrDisplay, foTime, foPath);
	var closeDialogHandler = function(event) {
		event.stop();
		layerObj.HideLayer();
	};
	// register onclick event for cancel button
	var elmt = $(htmlDialogElementId + 'ButtonCancel');
	if(elmt) {
		elmt.stopObserving('click'); // unregister all click events, because this method can be called several times, but only one click event should be exist.
		elmt.observe('click', closeDialogHandler);
	}
	if(actionHandler) {
		elmt = $(htmlDialogElementId + 'ButtonOk');
		elmt.stopObserving('click');
		elmt.observe('click', function(event) {
			actionHandler();
		});
	}
	else {
		// register default onclick event for ok button.
		elmt = $(htmlDialogElementId + 'ButtonOk');
		elmt.stopObserving('click');
		elmt.observe('click', closeDialogHandler);
	}
	// register default onclick event for ok button of post dialog
	var elmtArr = $$('.' + htmlDialogElementId + 'PostButtonOk');
	elmtArr.each(function(elmt) {
		elmt.stopObserving('click');
		elmt.observe('click', closeDialogHandler);
	});
	// only show content
	elmt = $(htmlDialogElementId + '_content');
	if(elmt) {
		elmt.show();
	}
	// hide success dialog
	elmt = $(htmlDialogElementId + '_success');
	if(elmt) {
		elmt.hide();
	}
	// hide error dialog
	elmt = $(htmlDialogElementId + '_error');
	if(elmt) {
		elmt.hide();
	}
	// hide waiting dialog
	elmt = $(htmlDialogElementId + '_waiting');
	if(elmt) {
		elmt.hide();
	}
	layerObj.ShowLayer();
}

function showSimpleModalWaitingDialog(htmlDialogElementId) {
	// hide main dialog
	var elmt = $(htmlDialogElementId + '_content');
	if(elmt) {
		elmt.hide();
	}
	// hide success dialog
	elmt = $(htmlDialogElementId + '_success');
	if(elmt) {
		elmt.hide();
	}
	// hide error dialog
	elmt = $(htmlDialogElementId + '_error');
	if(elmt) {
		elmt.hide();
	}
	showAjaxWaitingScreen(htmlDialogElementId + '_waiting');
}

function hideSimpleModalWaitingDialog(htmlDialogElementId) {
	hideAjaxWaitingScreen(htmlDialogElementId + '_waiting');
}

/**
 * @param clickEventHandler optional. determines action after click on OK button of success dialog.
 */
function showSimpleModalSuccessDialog(htmlDialogElementId, clickEventHandler) {
	var elmt = $(htmlDialogElementId + '_content');
	if(elmt) {
		elmt.hide();
	}
	elmt = $(htmlDialogElementId + '_success');
	if(elmt) {
		elmt.show();
	}
	if(clickEventHandler) {
		// register onclick event for ok button of post dialog
		var elmtArr = $$('.' + htmlDialogElementId + 'PostButtonOk');
		elmtArr.each(function(elmt) {
			// elmt.stopObserving('click');
			elmt.observe('click', clickEventHandler);
		});
	}
}

/**
 * @param ajaxResponse optional. uses it to show error code and message from AJAX response.
 */
function showSimpleModalErrorDialog(htmlDialogElementId, ajaxResponse) {
	var elmt = $(htmlDialogElementId + '_content');
	if(elmt) {
		elmt.hide();
	}
	elmt = $(htmlDialogElementId + '_error');
	if(elmt) {
		if(elmt.descendants().size() <= 1) { // if no message is given take one from AJAX response
			if(ajaxResponse) {
				var msg = 'Error code: ' + getAjaxResponseReturncode(ajaxResponse);
				msg += '<br/>Error message: ' + getAjaxResponseFirstNodeContentAsString(ajaxResponse);
				msg += '<br/>';
				elmt.insert({top:msg});
			}
			else { // if no error message is given at all, place this.
				elmt.insert({top:'Unknown error occurred. Action failed.<br/>'});
			}
		}
		elmt.show();
	}
}

function getAjaxResponseFirstNodeContentAsString(response) {
	var xmlDoc = response.responseXML;
	if(xmlDoc) {
		var elem = xmlDoc.firstChild;
		if(elem) {
			return elem.firstChild.data;
		}
	}
	return null;
}

/* Scans all elements of the given form and adds them as url params to the given url.
 * The resulting url is returned. */
function addFormElementsToUrl(url, formName) {
	Form.getElements($(formName)).each(function(item) {
//		if(typeof(console) !== 'undefined' && console != null) { console.log(item.id + ' => ' + item.value); }
		url += '&'+item.name+'='+encodeURIComponent(item.value);
	});	
	return url;
}

function clickLink(linkobj) {
    if (linkobj.getAttribute('onclick') == null) {
         if (linkobj.getAttribute('href')) document.location = linkobj.getAttribute('href');
    }
    else linkobj.onclick();
}


function setFlashHeight(divId, flashId, height) {
    if (document.getElementById(divId)) {
      document.getElementById(divId).style.height = parseInt(height) + 'px';
    }
    
    if (document.getElementById(flashId)) {
      document.getElementById(flashId).style.height = parseInt(height) + 'px';
    }
  }
  
  function setFlashWidth(divId, flashId, width) {
    if (document.getElementById(divId)) {
      document.getElementById(divId).style.width = parseInt(width) + 'px';
    }
    
    if (document.getElementById(flashId)) {
      document.getElementById(flashId).style.width = parseInt(width) + 'px';
    }
  }
  
  function setFlashSize(divId, flashId, width, height) {
    setFlashWidth(divid, flashId, width);
    setFlashHeight(divid, flashId, height);
  }

  function callFlash(flashID, functionToCall) {
    var functionString = 'document.getElementById("' + flashID + '").' + functionToCall;
    //alert(functionString + '   ...is about to be called!');
    eval(functionString);
  }
 
function dayChange(dayItem, monthItem, yearItem, selectedDay, dateField) {
	var selectedMonth = monthItem[monthItem.selectedIndex].value;
	var selectedYear = yearItem[yearItem.selectedIndex].value;
	validateDateOnFly(dayItem, selectedDay, selectedMonth, selectedYear, dateField);
}

function monthChange(dayItem, monthItem, yearItem, selectedMonth, dateField) {
	var selectedDay = dayItem[dayItem.selectedIndex].value;
	var selectedYear = yearItem[yearItem.selectedIndex].value;
	validateDateOnFly(dayItem, selectedDay, selectedMonth, selectedYear, dateField);
}

function yearChange(dayItem, monthItem, yearItem, selectedYear, dateField) {
	var selectedMonth = monthItem[monthItem.selectedIndex].value;
	var selectedDay = dayItem[dayItem.selectedIndex].value;
	validateDateOnFly(dayItem, selectedDay, selectedMonth, selectedYear, dateField);
}

// not related to validateDate above - this is called onchange - this level of validation was added after the
// function above - this alone should be sufficient
function validateDateOnFly(dayItem, selectedDay, selectedMonth, selectedYear, dateField) {
	var valid = true;
	if (selectedMonth == '4' || selectedMonth == '6' || selectedMonth == '9' || selectedMonth == '11') {
		if (selectedDay > 30) {
			valid = false;
			dayItem.selectedIndex = 0;
		}
	} else if (selectedMonth == '2') {
		if (selectedYear % 4 == 0) {
			// leap year
			if (selectedDay > 29) {
				valid = false;
				dayItem.selectedIndex = 0;
			}
		} else {
			if (selectedDay > 28) {
				valid = false;
				dayItem.selectedIndex = 0;
			}
		}
	}

	// put date in hidden field
	if(typeof(dateField) != "undefined") {
		if(valid && selectedDay != '' && selectedMonth != '' && selectedYear != '') {
			if(selectedDay.length == 1) selectedDay = '0'+selectedDay;
			if(selectedMonth.length == 1) selectedMonth = '0'+selectedMonth;
			var value = selectedYear + '-' + selectedMonth + '-' + selectedDay;
			if(document.getElementById(dateField)) {
				document.getElementById(dateField).value = value;
			}			
		} else {
			if(document.getElementById(dateField)) {
				document.getElementById(dateField).value = '';
			}			
		}		
	}
}