var globalPic;


 var _gaq = _gaq || [];
 _gaq.push(['_setAccount', 'UA-16824502-1']);
 _gaq.push(['_trackPageview']);

(function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

function setCurser(){
	if (document.forms.length > 0){
		var field = document.forms[0];
		for (i = 0; i < field.length; i++){
 			if ((field.elements[i].type == "text") || (field.elements[i].type == "textarea") || (field.elements[i].type.toString().charAt(0) == "s"))
 			{
 				document.forms[0].elements[i].focus();
 				break;
 			}
		}
	}
}

function preview(what){
  // valid file types
  var fileTypes=["jpg","jpeg"];
  // what to display when the image is not valid
  var defaultPic="images/spacer.gif";

  var source=what.value;
  var ext=source.substring(source.lastIndexOf(".")+1,source.length).toLowerCase();
  for (var i=0; i<fileTypes.length; i++) if (fileTypes[i]==ext) break;
  globalPic=new Image();
  alert(source);
  if (i<fileTypes.length) {
  	globalPic.src=source;
  } else {
    globalPic.src=defaultPic;
    alert("THAT IS NOT A VALID IMAGE\nPlease load an image with an extention of one of the following:\n\n"+fileTypes.join(", "));
  }
  // alert(globalPic.src + '\n' + globalPic.height + '\n' + globalPic.width);
  setTimeout("applyChanges()",200);
}
function applyChanges(){
  // width to resize large images to
  var maxWidth=200;
  // height to resize large images to
  var maxHeight=200;
  // the id of the preview image tag
  var outImage="previewField";
 
  var field=document.getElementById(outImage);
  var x=parseInt(globalPic.width);
  var y=parseInt(globalPic.height);
  if (x>maxWidth) {
    y*=maxWidth/x;
    x=maxWidth;
  }
  if (y>maxHeight) {
    x*=maxHeight/y;
    y=maxHeight;
  }
  field.style.display=(x<1 || y<1)?"none":"";
  field.src=globalPic.src;
  field.width=x;
  field.height=y;
}


//dampft leerzeichen(-sequenzen) innerhalb einer zeichenkette auf ein einzelnes "space" ein;
function superTrim(str) {
    return(str.replace(/\s+/g," ").replace(/\s+$/,"").replace(/^\s+/,""));
  };

function escapeHTML (str)
{
   var a = str.replace(/"/g,'&quot;');
   a = a.replace (/'/g,'&#039;');
   a = a.replace (/&/g,'&amp;');
   a = a.replace (/</g,'&lt;');
   a = a.replace (/>/g,'&gt;');
   return a;
}

function checkAll(field)
{
	for (i = 0; i < field.length; i++)
		field[i].checked = true ;
}

function uncheckAll(field)
{
	for (i = 0; i < field.length; i++)
		field[i].checked = false ;
}

function getCheckedCount(field)
{
	var counter = 0;
	for (i = 0; i < field.length; i++)
		if (field[i].checked == true) counter+=1;
	return counter;
}


function storeCaret (textEl) {
   if (textEl.createTextRange) 
     textEl.caretPos = document.selection.createRange().duplicate();
}

function insertAtCaret(obj, string)
{
	obj.focus();
	if (typeof(document.selection) != 'undefined')
	{
		var range = document.selection.createRange();
		if (range.parentElement() != obj)
			return;
		range.text = string;
		range.select();
	}
	else if (typeof(obj.selectionStart) != 'undefined')
	{
		var start = obj.selectionStart;
		obj.value = obj.value.substr(0, start) 
			+ string 
			+ obj.value.substr(obj.selectionEnd, obj.value.length);
		start += string.length;
		obj.setSelectionRange(start, start);
	}
	else
		obj.value += string;
		obj.focus();
}


function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   }
   return this
}

function isValidDate(dtStr){

	var dtCh= ".";
	var minYear=1900;
	var maxYear=2100;

	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("Das Datumsformat sollte wie folgt aussehen : tt.mm.jjjj")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Bitte einen gültigen Monat eingeben")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Bitte einen gültigen Tag eingeben")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Bitte einen gültiges, vierstelliges Jahr zwischen "+minYear+" und "+maxYear+" eingeben")
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Bitte ein gültiges Datum eingeben")
		return false
	}
	return true
}



/* Ajax Functions */

function callAjaxRequest(functioname) {
  var parameterlist;
  var parametercount = 0;
  var parameters;
  var retvalue;
  // iterate through non-separator arguments
  for (var i = 1; i < arguments.length; i++) {
    parameterlist += '&arg_' + parametercount + '=' + arguments[i]; 
	parametercount ++;
  }
  parameters = 'function=' + functioname + '&argcount=' + parametercount + parameterlist;
  new Ajax.Request('modules/fktAjax.php',{
      method:'get',
	  asynchronous: false,
	  encoding:'UTF-8',     
      parameters:parameters,
      onSuccess: 
      	function(e){
      	  retvalue = e.responseText;
      	}
      }
    );
    
    return retvalue;
}



/* Tooltip Functions */

function doTooltipSimple(e, msg) {
  if ( typeof Tooltip == "undefined" || !Tooltip.ready ) {
  	return;
  }
  Tooltip.show(e, msg);
}

function hideTipSimple() {
  if ( typeof Tooltip == "undefined" || !Tooltip.ready ) return;
  Tooltip.hide();
}

function doTooltip(e, msg) {
  if ( typeof Tooltip == "undefined" || !Tooltip.ready ) return;
  Tooltip.clearTimer();
  var tip = document.getElementById? document.getElementById(Tooltip.tipID): null;
  if ( tip && tip.onmouseout == null ) {
      tip.onmouseout = Tooltip.tipOutCheck;
      tip.onmouseover = Tooltip.clearTimer;
  }
  Tooltip.show(e, msg);
}


function hideTip() {
  if ( typeof Tooltip == "undefined" || !Tooltip.ready ) return;
  Tooltip.timerId = setTimeout("Tooltip.hide()", 300);
}


// returns true of oNode is contained by oCont (container)
function contained(oNode, oCont) {
  if (!oNode) return; // in case alt-tab away while hovering (prevent error)
  while ( oNode = oNode.parentNode ) if ( oNode == oCont ) return true;
  return false;
}


function initializeTooltip(){
	Tooltip.init();
	Tooltip.offX = 1;  
	Tooltip.offY = 1;
	Tooltip.followMouse = false;  // must be turned off for hover-tip

	Tooltip.timerId = 0;
	Tooltip.clearTimer = function() {
	  if (Tooltip.timerId) { clearTimeout(Tooltip.timerId); Tooltip.timerId = 0; }
	}

	Tooltip.tipOutCheck = function(e) {
	  e = dw_event.DOMit(e);
	  // is element moused into contained by tooltip?
	  var toEl = e.relatedTarget? e.relatedTarget: e.toElement;
	  if ( this != toEl && !contained(toEl, this) ) Tooltip.hide();
	}
	
	Tooltip.unHookHover = function () {
	    var tip = document.getElementById? document.getElementById(Tooltip.tipID): null;
	    if (tip) {
	        tip.onmouseover = null; 
	        tip.onmouseout = null;
	        tip = null;
	    }
	}
	
	dw_event.add(window, "unload", Tooltip.unHookHover, true);
}

function hideTipAjax() {
  if ( typeof Tooltip == "undefined" || !Tooltip.ready ) return;
  Tooltip.timerId = setTimeout("Tooltip.hide()", 300);
}

function doTooltipAjaxMemberData(elem, memberId) {
  if ( typeof Tooltip == "undefined" || !Tooltip.ready ) return;
  Tooltip.clearTimer();
  var tip = document.getElementById? document.getElementById(Tooltip.tipID): null;
  if ( tip && tip.onmouseout == null ) {
      tip.onmouseout = Tooltip.tipOutCheck;
      tip.onmouseover = Tooltip.clearTimer;
  }

  ttt = callAjaxRequest('GetFormattedMemberData', memberId);
  Tooltip.show(elem, ttt);
}

function doTooltipAjaxCalYearDay(elem, seldate) {
  /*
  if ( typeof Tooltip == "undefined" || !Tooltip.ready ) return;
  Tooltip.clearTimer();
  var tip = document.getElementById? document.getElementById(Tooltip.tipID): null;
  if ( tip && tip.onmouseout == null ) {
      tip.onmouseout = Tooltip.tipOutCheck;
      tip.onmouseover = Tooltip.clearTimer;
  }
  */

  if ( typeof Tooltip == "undefined" || !Tooltip.ready ) {
  	return;
  }
  
  ttt = callAjaxRequest('GetDayInformation', seldate);
  
  // Tooltip nur dann zeigen, wenn an dem Tag ein definiertes Ereignis existiert
  if (ttt != '') {
  	Tooltip.show(elem, ttt);
  }
  

}

function handleDeadline(newValue) {
	if (newValue == true) {
		document.getElementById('imgCalAschluss').style.visibility = "visible";
		document.getElementById('imgCalAschluss').disabled = false;
		document.getElementById('inASchluss').disabled = false;
	} else {
		document.getElementById('imgCalAschluss').style.visibility = "hidden";
		document.getElementById('imgCalAschluss').disabled = true;
		document.getElementById('inASchluss').disabled = true;
	}
	//alert(newValue);
}


function IsEmptyString(sToCheck) {
   var sTest;
   if (sToCheck != null) {
	  sTest = superTrim(sToCheck);
   	  if(sTest == "") {	
      	return true;
      }
   }
   return false;
}

function mailwithsubject(adresslist, subject) {
	location.href='mailto:' + adresslist +'?subject='+ escape(subject); 
}


function submitenterlogon(myfield,e) {
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;
	
	if (keycode == 13)
	   {
	   SetAction('logon','member.php');
	   return false;
	   }
	else
	   return true;
}

function IgnoreReturn(myfield, e) {
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;
	
	if (keycode == 13)
	   return false;
}

function WriteToClipBoard(strValue) {
 	window.clipboardData.setData("Text", strValue);
}

function CopyAdressesToClipboard(field) {
    var strAdresses = '';
    if (getCheckedCount(document.frmMain.elements['membermails[]']) == 0) {
   		alert('Es muss mindestens ein Mitglied ausgewählt sein');
   		return;
    }

	for (i = 0; i < field.length; i++) {
		if(field[i].checked && field[i].value.length > 0) {
            if(strAdresses.length == 0) strAdresses = field[i].value;
            else strAdresses += ',' + field[i].value;
        }
	}

	WriteToClipBoard(strAdresses);
	alert('Die Email Adressen der ausgewählten Mitglieder wurden in die Zwischenablage kopiert und können so in anderen Programmen eingefügt werden.');
}

