/**
 * ...
 *
 * @author $Author: daniel $
 * @version $Revision: 1.1.2.14 $
 *
 * $Log: functions.js,v $
 * Revision 1.1.2.14  2009/11/02 10:36:55  daniel
 * fixed ajax calls getActivities()
 *
 * Revision 1.1.2.13  2009/11/02 10:15:14  daniel
 * fixed 'hide_options' handling
 *
 * Revision 1.1.2.12  2009/10/29 14:16:46  daniel
 * updated width and height calculation of dialogs
 *
 * Revision 1.1.2.11  2009/10/23 10:00:24  daniel
 * added activity log functions
 *
 * Revision 1.1.2.10  2009/04/16 14:00:21  ronny
 * use scrollable dialogs
 *
 * Revision 1.1.2.9  2009/03/03 08:34:20  daniel
 * init vars
 *
 * Revision 1.1.2.8  2009/02/10 16:50:21  ronny
 * use auto scrolling in iframe window
 *
 * Revision 1.1.2.7  2009/02/10 11:24:15  daniel
 * updated modal popup styling
 *
 * Revision 1.1.2.6  2009/02/10 10:42:59  daniel
 * moved popup functions to functions.js
 *
 * Revision 1.1.2.5  2009/02/09 11:12:40  ronny
 * add serverTimeFunctions
 *
 * Revision 1.1.2.4  2008/10/22 12:17:08  daniel
 * updated CheckAll()
 *
 * Revision 1.1.2.3  2008/07/02 09:02:49  daniel
 * *** empty log message ***
 *
 * Revision 1.1.2.2  2008/04/25 09:51:14  daniel
 * merged with functions from shop/includes/functions.js
 *
 * Revision 1.1.2.1  2008/04/25 09:35:28  daniel
 * moved www/members/javascript to www/javascript
 *
 * Revision 1.1.8.2  2008/03/18 15:21:00  daniel
 * fixed: xhtml requires lowercase name-attribut (CheckAll)
 *
 * Revision 1.1.8.1  2008/01/18 07:40:06  daniel
 * merged with 'cosis_frameless'
 *
 * Revision 1.1  2007/04/16 08:20:34  daniel
 * added search suggestions
 *
 *
 */
function callAction(action) {
	window.location=action;
	//document.messages_filter.submit();
	//alert(action);
}

function confirmSearch(text) {
	var result = window.confirm(text);
	return result;
}

function isEmail(s) {
	var a = false;
	var res = false;
	if(typeof(RegExp) == 'function') {
		var b = new RegExp('abc');
		if(b.test('abc') == true) {
			a = true;
		}
	}
	if(a == true) {
		reg = new RegExp('^([a-zA-Z0-9\\-\\.\\_]+)'+'(\\@)([a-zA-Z0-9\\-\\.]+)'+'(\\.)([a-zA-Z]{2,4})$');
		res = (reg.test(s));
	} else {
		res = (s.search('@') >= 1 && s.lastIndexOf('.') > s.search('@') && s.lastIndexOf('.') >= s.length-5)
	}
	return(res);
}

function checkMail(field_id) {
	email_field = document.getElementById(field_id);
	if (email_field.value != "") {
		//clean up
		term_email_current=email_field.value;
		term_email_clean=term_email_current.replace(/[^\wßüöä@\.\-\_]/gi, "");
		email_field.value = term_email_clean;
	}
	if (email_field.value == "") {
		alert("Please enter mail address!");
		email_field.focus();
		return false;
	}
	if (!isEmail(email_field.value)) {
		email_field.focus();
		return confirmSearch('This is not a valid mail address (name@address.com):\n\n' + email_field.value + '\n\n' + 'Do you want to continue?\n');
	}
}

function CheckAll(formname){
	if(document.forms[formname].all){
		var c = document.forms[formname].all.checked;
	}
	for (var i=0;i<document.forms[formname].elements.length;i++){
		var e = document.forms[formname].elements[i];
		if(e.name != 'all') e.checked = c;
	}
}

function reset_CheckAll(formname){
	check=1;
	for (var i=0;i<document.forms[formname].elements.length;i++){
		var e = document.forms[formname].elements[i];
		if(e.name != 'all' && e.checked==0 && e.type=='checkbox') check=0;
	}
	if(document.forms[formname].all){
		document.forms[formname].all.checked=check;
	}
}

function leftTrim(sString) {
	while (sString.substring(0,1) == ' ') {
		sString = sString.substring(1, sString.length);
	}
	return sString;
}

function rightTrim(sString) {
	while (sString.substring(sString.length-1, sString.length) == ' ') {
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
}

function trimAll(sString)
{
	while (sString.substring(0,1) == ' ') {
		sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == ' ') {
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
}

function itemToggleVisibility(itemID) {
	var x=document.getElementsByName(itemID)
	for(var i=0; i<x.length; i++) {
		var current = x[i].style.visibility;
		if(x[i].style.visibility=='collapse')
			x[i].style.visibility='visible';
		else
			x[i].style.visibility='collapse';
	}
}

function searchUL(UL) {
	do {
		if(UL) UL = UL.nextSibling;
		if(UL && UL.nodeName == "UL") return UL;
	} while(UL);
	return false;
}

function showBlock(id) {
	var LI = document.getElementById(id);
	var UL = searchUL(LI.firstChild);
	UL.style.display = "block";
	UL.style.visibility = "visible";
}

function hideBlock(id) {
	var LI = document.getElementById(id);
	var UL = searchUL(LI.firstChild);

	var check = LI.className;
	if(!check.match(/expanded/i)) {
		//aktiven zweig nicht schliessen!
		UL.style.display = "none";
		UL.style.visibility = "hidden";
	}
}

function showElement(element_id) {
	var element = document.getElementById(element_id);
	if(element) {
		element.style.display = "block";
	}
}

function hideElement(element_id) {
	var element = document.getElementById(element_id);
	if(element) {
		element.style.display = "none";
	}
}

function setAutocompleter(autocomleter, inputID, suggestID, sourceKeyID, wordKeyID, resetInput) {
	if(resetInput=='true') {
		var inputField = document.getElementById(inputID);
		inputField.value='';
	}
	var sourceKey = document.getElementById(sourceKeyID);
	search_query_sourcekey = sourceKey.value;
	var wordKey = document.getElementById(wordKeyID);
	search_query_wordkey = wordKey.options[wordKey.selectedIndex].value;
	autocomleter = new Ajax.Autocompleter(inputID,suggestID,'/members/rpc.php?mode=search_suggest', {minChars: 2, tokens: ' ', select:'selectme', method:'get', parameters:'type=relations&source_key='+search_query_sourcekey+'&word_key='+search_query_wordkey, paramName:'query', autoSelect:false, asynchronous:false});
}

function setSearchKeyword(selectorID, inputID) {
	var selector = document.getElementById(selectorID);
	var inputField = document.getElementById(inputID);
	inputField.value=selector.options[selector.selectedIndex].value;
}

function clearFormField(field, checkInput) {
	if(field.value==checkInput) {
		field.value='';
	}
}

function setFieldValue(fieldID, fieldValue) {
	var e = document.getElementById(fieldID);
	e.value=fieldValue;
}

function updateFieldValue(source, destination) {
	var src = document.getElementById(source);
	var dst = document.getElementById(destination);
	dst.value = src.value;
}

function padlength(what){
	var output=(what.toString().length==1)? "0"+what : what
	return output
}

function displaytime(timerID, timerVar, noinc){
	if(!noinc)
		timerVar.setSeconds(timerVar.getSeconds()+1);
	var datestring=padlength(timerVar.getDate())+"."+padlength(timerVar.getMonth()+1)+"."+timerVar.getFullYear()
	var timestring=padlength(timerVar.getHours())+":"+padlength(timerVar.getMinutes())+":"+padlength(timerVar.getSeconds())
	document.getElementById(timerID).innerHTML=datestring+" "+timestring
}

function confirm_submit(text) {
	if(!text || text=="") text="Perform action?";
	return confirm(text);
}

function confirm_select(select, text) {
	opt=document.getElementById(select);
	selectID=opt.selectedIndex;
	if(opt[selectID].value!='') {
		confirm_text='';
		if(text!='') {
			confirm_text=confirm_text+text+"\n\n";
		}
		confirm_text=confirm_text+opt[selectID].text;
		confirm_text=confirm_text+'?';
		return confirm(confirm_text);
	}
	return false;
}

function showRequest(formData, jqForm, options) {
    var queryString = $.param(formData);
    alert('About to submit: \n\n' + queryString);
    return true;
}

function showResponse(responseText, statusText)  {
    alert('status: ' + statusText + '\n\nresponseText: \n' + responseText +
        '\n\nThe output div should have already been updated with the responseText.');
}

/*
 * Server Time Functions
 */

var _serverTimeOffset = 0;
var _serverTimeInterval = null;
var _localTimeDiv = null;
var _serverTimeDiv = null;
var _autoLogoutDiv = null;
var _sessionEnd = 0;

function startServerTime(config) {
	var localtime = new Date();
	if (config) {
		if (config.localTimeID) {
			_localTimeDiv = document.getElementById(config.localTimeID);
		}
		if (config.serverTimeID) {
			_serverTimeDiv = document.getElementById(config.serverTimeID);
		}
		if (config.autoLogoutTimeID) {
			_autoLogoutDiv = document.getElementById(config.autoLogoutTimeID);
		}
		if (config.time) {
			_serverTimeOffset = config.time - localtime.getTime();
		}
		if (config.sessionEnd) {
			_sessionEnd = config.sessionEnd;
		}
		_serverTimeInterval = window.setInterval("displayServerTime()", 1000);
	}
}

function displayServerTime() {
	var hours, minutes, seconds;
	var logoutmsec, logouttime;
	var localtime = new Date();
	var servertime = new Date(localtime.getTime() + _serverTimeOffset);
	if (_localTimeDiv) {
		hours = localtime.getHours();
		minutes = localtime.getMinutes();
		seconds = localtime.getSeconds();
		hours   = ((hours < 10)   ? '0' + hours   : hours);
		minutes = ((minutes < 10) ? '0' + minutes : minutes);
		seconds = ((seconds < 10) ? '0' + seconds : seconds);
		_localTimeDiv.innerHTML = '' + hours + ':' + minutes + ':' + seconds;
	}
	if (_serverTimeDiv) {
		hours = servertime.getHours();
		minutes = servertime.getMinutes();
		seconds = servertime.getSeconds();
		hours   = ((hours < 10)   ? '0' + hours   : hours);
		minutes = ((minutes < 10) ? '0' + minutes : minutes);
		seconds = ((seconds < 10) ? '0' + seconds : seconds);
		_serverTimeDiv.innerHTML = '' + hours + ':' + minutes + ':' + seconds;
	}
	if (_autoLogoutDiv) {
		logoutmsec = _sessionEnd - servertime.getTime();
		if (logoutmsec > 0) {
			logouttime = new Date(logoutmsec);
			hours = logouttime.getUTCHours();
			minutes = logouttime.getUTCMinutes();
			seconds = logouttime.getUTCSeconds();
			hours   = ((hours < 10)   ? '0' + hours   : hours);
			minutes = ((minutes < 10) ? '0' + minutes : minutes);
			seconds = ((seconds < 10) ? '0' + seconds : seconds);
			_autoLogoutDiv.innerHTML = '' + hours + ':' + minutes + ':' + seconds;
		} else {
			_autoLogoutDiv.innerHTML = '';
		}
	}
}

function stopServerTime() {
	window.clearInterval(_serverTimeInterval);
}

function openModalPopup(url, title, width, height, options) {
	if(typeof width == 'undefined' || width == '')
		var width = 400;
	if(typeof height == 'undefined' || height == '')
		var height = 400;
	if(typeof title == 'undefined')
		var title = '';
	if(typeof options == 'undefined')
		var options = {};

	var defaults = {
		dialogClass: 'cosis-dialog cosis-dialog-iframe',
		height: (height+10+29+10), /* height content + margin content + height header + unknown */
		width: (width+10), /* width content + margin content */
		bgiframe: true,
		modal: true,
		overlay: {
			opacity: 0.3,
			background: '#000000'
		},
		draggable: false,
		resizable: false,
		title: title
	};
	var dialog = $('<div></div>');
	$(dialog).load(url);
	$(dialog).dialog($.extend(defaults, options));
	return false;
}

function openModalPopupIframe(url, title, width, height, options) {
	if(typeof width == 'undefined' || width == '')
		var width = 400;
	if(typeof height == 'undefined' || height == '')
		var height = 400;
	if(typeof title == 'undefined')
		var title = '';
	if(typeof options == 'undefined')
		var options = {};

	var defaults = {
		dialogClass: 'cosis-dialog cosis-dialog-iframe',
		height: (height+10+29+5), /* height content + margin content + height header + unknown */
		width: (width+10), /* width content + margin content */
		bgiframe: true,
		modal: true,
		overlay: {
			opacity: 0.3,
			background: '#000000'
		},
		draggable: false,
		resizable: false,
		title: title
	};
	var body = '<div><iframe style="border:0;margin:10px 5px 5px 5px;padding:0;"scrolling="auto" marginheight="0" marginwidth="0" frameborder="0" src="'+url+'" width="'+width+'" height="'+height+'">Your browser doesn\'t supports iframes!<br>Click <a href="javascript:void(0)" onclick="javascript:return fenster(\''+url+'\','+width+','+height+');">here</a></iframe></div>';
	cosisDialogOpen(title, body, $.extend(defaults, options));
	//var dialog = $(body);
	//$(dialog).dialog($.extend(defaults, options));
	return false;
}

function openModalPopupContent(content, title, width, height, options) {
	if(typeof width == 'undefined' || width == '')
		var width = 400;
	if(typeof height == 'undefined' || height == '')
		var height = 400;
	if(typeof title == 'undefined')
		var title = '';
	if(typeof options == 'undefined')
		var options = {};

	var defaults = {
		dialogClass: 'cosis-dialog cosis-dialog-iframe',
		height: (height+10+29+10), /* height content + margin content + height header + unknown */
		width: (width+10), /* width content + margin content */
		bgiframe: true,
		modal: true,
		overlay: {
			opacity: 0.3,
			background: '#000000'
		},
		draggable: false,
		resizable: false,
		title: title
	};
	$(content).dialog($.extend(defaults, options));
	return false;
}

function getActivityLog(target, user, hide_options) {
	var $target = $(target);
	var user = (user) ? user : '';
	var hide_options = (hide_options) ? 1 : '';
	if($target.length) {
		$.ajax({
			cache: false,
			async: false,
			type: 'POST',
			url: '/members/rpc/profile.php',
			data: {
				action: 'getActivityLog',
				user: user,
				hide_options: hide_options
			},
			success: function(response){
				$target.html(response);
				//register delete
				$target.find("a.activity-item-delete").click(function(e) {
					var entry = $(this).attr('rel');
					if(entry.length) {
						deleteActivityLogEntry(target, entry);
					}
					return false;
				});
			}
		});
	}
	return false;
}

function deleteActivityLogEntry(target, entry) {
	var $target = $(target);
	if($target.length) {
		$.ajax({
			cache: false,
			async: false,
			type: 'POST',
			url: '/members/rpc/profile.php',
			data: {
				action: 'deleteActivityLogEntry',
				entry: entry
			},
			success: function(response){
				getActivityLog(target);
			}
		});
	}
	return false;
}