/*
// File written by Jochen "Khuri" Höhmann <khuri@khuris.com>
// Copyright 2011
//
// File        : shared.js
// Begin       : 2010.01.26 17:46:02
// Last Update : 2011.07.05 16:16:56
*/

// <![CDATA[
var request = null;
var clientbrowser = navigator.userAgent.toLowerCase();
var is_ie = ((clientbrowser.indexOf("msie") != -1) && (clientbrowser.indexOf("opera") == -1));
var is_nav = ((clientbrowser.indexOf('mozilla')!=-1) && (clientbrowser.indexOf('compatible') == -1));
var ie_version = getInternetExplorerVersion();

function getInternetExplorerVersion() {
	// From MSDN
	// Returns the version of Internet Explorer or a -1
	// (indicating the use of another browser).
  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer') {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}

// Handle onload events
function addonload(func) {
	if(typeof func == 'function') {
	  var oldonload = window.onload;
	  if(typeof window.onload != 'function') {
	    window.onload = func;
	  }
	  else {
	    window.onload = function() {
	      if(oldonload) {
	        oldonload();
	      }
	      func();
	    }
	  }
	}
}

// Statusbox
function statusbox_close() {
	document.getElementById('statusbox').style.visibility='hidden';
	document.getElementById('statusbox').style.display='none';
}

/* Go somewhere else */
function goto(where,wwindow) {
	if(wwindow != 0 && typeof wwindow != "undefined") {
		if(where != 0) {
			if(wwindow.closed == true || !wwindow.document) {
				wwindow = window.open(where,wwindow);
			}
			wwindow.location.href=where;
		}
		wwindow.focus();
	}
	else {
		window.location.href=where;
	}
}

/* Confirm stuff */
function confirm_check(id) {
	check_opt = confirm("Sind Sie sicher, dass Sie diese Option markieren wollen?");
	document.getElementById(id).checked = (check_opt) ? true : false;
}
function confirm_action(what,where) {
	checki = confirm(what);
	if(checki == true) {
		goto(where);
	}
}
function isdefined(variable) {
	return (this[variable] === undefined) ? false : true;
}


/* Calendar functions */
function calendar_draw(box,iswitch,year,month,justdate) {
	document.getElementById('calendar_'+box).value = document.getElementById('calendar_'+box).value.replace(/^\s*(S)\s*$/, '$1');
	if(calendar_checkdate(document.getElementById('calendar_'+box).value,justdate)) {
		if(document.getElementById('calendar_'+box).value != '') {
			var fieldvalue = (justdate == 1) ? document.getElementById('calendar_'+box).value.replace(/(19|20)?([0-9]{2})[\- \/.](1[012]|0?[1-9])[\- \/.](3[01]|[12][0-9]|0?[1-9])?/ig,"$1$2-$3-$4").split("-") : document.getElementById('calendar_'+box).value.replace(/(19|20)?([0-9]{2})[\- \/.](1[012]|0?[1-9])[\- \/.](3[01]|[12][0-9]|0?[1-9])(?:[\- \/.]([01][0-9]|2[0-4])[:.]([0-5][0-9]))?/ig,"$1$2-$3-$4-$5-$6").split("-");
			if(!cdate) {
				var cdate = new Date(fieldvalue[0],(fieldvalue[1] -1),1);
			}
		}
		// only check display setting if required
		if(iswitch > 0 && iswitch < 3) {
			var cblock = (iswitch == 1) ? document.getElementById('calendarbox_'+box).style.display : "block";
			if(document.getElementById('calendarbox_on')) {
				document.getElementById('calendarbox_on').style.display="none";
			}
			if(document.getElementById('calendarbox_off')) {
				document.getElementById('calendarbox_off').style.display="none";
			}
			document.getElementById('calendarbox_'+box).style.display=(cblock == "block") ? "none" : "block";
			if(iswitch == 2) {
				return;
			}
		}
		// only 3 possible options, existing date is valid, invalid or the click is simply a date switch
		if(year > 0 && month >= 0) {
			var cdate = new Date(year,month,1);
		}
		if(iswitch < 3) {
			if(!cdate) {
				var cdate = new Date(new Date().getFullYear(),new Date().getMonth(),1);
			}
			var month_array = new Array("Januar","Februar","M&auml;rz","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember");
			var cday = cdate.getDate();
			var cmonth = cdate.getMonth();
			var cyear = cdate.getFullYear();
			var cwday = cdate.getDay();
			cwday = (cwday == 0) ? 7 : cwday;
			// calculate days of month
			var cmdays = 31;
			while(cmonth != new Date(cyear,cmonth,cmdays).getMonth()) {
				cmdays--;
				if(cmdays == 0) break;
			}
			if(cblock != "block") {
				// clean calendar box and start drawing, and because i'm lazy it's all innerHTML only
				var cbox = '';
				cbox += '<table class="jscalendar" cellpadding=0 cellspacing=1><thead><tr>';
				cbox += '<th class="switch" onclick="calendar_draw(\''+box+'\',0,'+(((cmonth -1) > -1) ? cyear : (cyear -1))+','+(((cmonth -1) > -1) ? (cmonth -1) : 11)+','+((justdate != 1) ? 0 : 1)+');">&lt;&lt;<\/th>';
				cbox += '<th colspan=5>'+month_array[cmonth]+' '+cyear+' <span>';
				cbox += '<a onclick="calendar_draw(\''+box+'\',0,'+(cyear +1)+','+(cmonth)+','+((justdate != 1) ? 0 : 1)+');">+<\/a>|<a onclick="calendar_draw(\''+box+'\',0,'+(cyear -1)+','+(cmonth)+','+((justdate != 1) ? 0 : 1)+');">-<\/a>';
				cbox += '<\/span><\/th>';
				cbox += '<th class="switch" onclick="calendar_draw(\''+box+'\',0,'+(((cmonth +1) < 12) ? cyear : (cyear +1))+','+(((cmonth +1) < 12) ? (cmonth +1) : 0)+','+((justdate != 1) ? 0 : 1)+');">&gt;&gt;<\/th>';
				cbox += '<\/tr><\/thead>';
				cbox += '<tbody><tr>';
				// Weekday names
				for(i=0;i<7;i++) {
					cbox += '<th>'+"MDMDFSS".substr(i,1)+'<\/th>';
				}
				cbox += '<\/tr><tr>';
				// Weeks and days
				for(i=1;i<=42;i++) {
					// do markings
					showclass = '';
					showclass += (i-cwday +1 == new Date().getDate() && cmonth == new Date().getMonth() && cyear == new Date().getFullYear()) ? ' today' : '';
					showclass += (i%7==0) ? ' sunday' : '';
					showclass += ((fieldvalue) ? ((i-cwday +1 == fieldvalue[2] && cmonth == (fieldvalue[1] -1) && cyear == fieldvalue[0]) ? ' markday' : '') : '');
					cbox += '<td class="'+showclass+(((i-cwday +1 >0) && (i-cwday +1<=cmdays))?'':' inactive')+'" '+(((i-cwday +1 >0) && (i-cwday +1<=cmdays))?'onclick="this.parentNode.parentNode.lastChild.firstChild.firstChild.value=\''+cyear+'-'+((cmonth +1 < 10) ? '0' : '')+(cmonth +1)+'-'+((i-cwday +1 < 10) ? '0' : '')+(i-cwday +1)+'\';'+((justdate != 1) ? 'this.parentNode.parentNode.lastChild.firstChild.childNodes[1].select();this.parentNode.parentNode.lastChild.firstChild.childNodes[1].focus();' : '')+'calendar_markday(this);"' : '')+'>'+(((i-cwday>=0) && (i-cwday<cmdays)) ? (i-cwday +1) : '&nbsp;')+'<\/td>';
					cbox += (i%7==0 && i<36) ? '<\/tr><tr>' : '';
					// terminate box if we're about to draw an empty row
					if(i%7==0 && (i-cwday +1>=cmdays)) {
						break;
					}
				}
				cbox += '<\/tr><tr>';
				if(justdate != 1) {
					// create the timefields
					cbox += '<th colspan=3><input type="hidden" name="calendar_date" value="'+((fieldvalue) ? (fieldvalue[0]+'-'+fieldvalue[1]+'-'+fieldvalue[2]) : cyear+'-'+((cmonth+1 < 10) ? '0'+cmonth+1 : cmonth+1)+'-'+((cday < 10) ? '0'+cday : cday))+'">';
					cbox += '<input type="text" size="2" maxlength="2" class="courier" name="calendar_hour" value="'+((fieldvalue) ? ((fieldvalue[3] != '') ? fieldvalue[3] : 15) : 15)+'" tabindex=1> : <input type="text" size="2" maxlength="2" class="courier" name="calendar_min" value="'+((fieldvalue) ? ((fieldvalue[4] != '') ? fieldvalue[4] : '00') : '00')+'" tabindex=2><\/th>';
				}
				cbox += '<th colspan='+((justdate != 1) ? 4 : 7)+'><button type="button" class="set" onclick="calendar_adddate(\''+box+'\',this.parentNode.parentNode.firstChild.childNodes[0].value'+((justdate != 1) ? '+\' \'+this.parentNode.parentNode.firstChild.childNodes[1].value+\':\'+this.parentNode.parentNode.firstChild.childNodes[3].value,0' : ',1')+');" tabindex=3>setzen</button><\/th>';
				// end the table
				cbox += '<\/tr><\/table>';
				document.getElementById('calendarbox_'+box).innerHTML = cbox;
			}
		}
	}
}
function calendar_adddate(box,cstring,justdate) {
	document.getElementById('calendar_'+box).value=cstring;
	calendar_draw(box,2,0,0,justdate);
}
function calendar_markday(who) {
	for(i=1;i<=6;i++) {
		for(z=0;z<who.parentNode.parentNode.childNodes[i].childNodes.length;z++) {
			if(who.parentNode.parentNode.childNodes[i].childNodes[z].tagName.toLowerCase() == "td") {
				newclass = who.parentNode.parentNode.childNodes[i].childNodes[z].className.replace(/markday/ig, "");
				who.parentNode.parentNode.childNodes[i].childNodes[z].className = newclass+((who.parentNode.parentNode.childNodes[i].childNodes[z].innerHTML == who.innerHTML) ? " markday" : "");
			}
		}
	}
}
function calendar_checkdate(cstring,justdate) {
	if(justdate != 1) {
		if(/^(?:(19|20)?([0-9]{2})[\- \/.](1[012]|0?[1-9])[\- \/.](3[01]|[12][0-9]|0?[1-9])(?:[\- \/.]([01][0-9]|2[0-4])[:.]([0-5][0-9])))$/i.test(cstring) || cstring == "") {
			return true;
		}
		alert("Ihr Datum ist leider ungueltig.\nBitte verwenden Sie folgendes Format:\nJJJJ-MM-TT HH:MM");
	}
	else {
		if(/^(?:(19|20)?([0-9]{2})[\- \/.](1[012]|0?[1-9])[\- \/.](3[01]|[12][0-9]|0?[1-9]))$/i.test(cstring) || cstring == "") {
			return true;
		}
		alert("Ihr Datum ist leider ungueltig.\nBitte verwenden Sie folgendes Format:\nJJJJ-MM-TT");
	}
	return false;
}

// Object fading
var banner_fadespeed = 50;
var banner_fademultiply = 20;
var fadelock = 0;

function opac(i,elmnt,init) {
	fadelock = 1;
	var vobj = document.getElementById(elmnt).style;
	vobj.opacity = (i / banner_fademultiply);
	vobj.MozOpacity = (i / banner_fademultiply);
	vobj.KhtmlOpacity = (i / banner_fademultiply);
	vobj.filter = "alpha(opacity="+(i * (1 / banner_fademultiply * 100))+")";
	if(init > 0) {
		if(init == 2) {
			for(var n=0;n<=banner_fademultiply;n++) {
				window.setTimeout("opac("+n+",'"+elmnt+"',0);",(n * banner_fadespeed));
			}
		}
		else {
			for(var n=banner_fademultiply;n>=0;n--) {
				window.setTimeout("opac("+n+",'"+elmnt+"',0);",((banner_fademultiply - n) * banner_fadespeed));
			}
		}
	}
	if(i == banner_fademultiply) {
		fadelock = 0;
		return true;
	}
}

function switch_image(ref,imgpath,imglist,targetid,direction) {
	var targetimg = document.getElementById(targetid);
	var cimg = targetimg.src.substr(targetimg.src.lastIndexOf("/")+1);
	var imglist = imglist.split(",");
	var reftext = ref.parentNode.innerHTML;
	for(var i=0;i<imglist.length;i++) {
		if(imglist[i] == cimg) {
			var ci = 0;
			if(direction == "left") {
				ci = (i == 0) ? (imglist.length -1) : i-1;
			}
			else {
				ci = (i == (imglist.length -1)) ? 0 : i+1;
			}
			targetimg.src = imgpath+imglist[ci];
			reftext = reftext.replace(/(.*?)>(.*?)([0-9]+)(.*?)([0-9]+)(.*?)<(.*?)/g, "$1>$2"+(ci+1)+"$4"+imglist.length+"$6<$7");
			ref.parentNode.innerHTML = reftext;
			break;
		}
	}
	return true;
}

// Check the content of a form (using CSS classes)
function checkform(ref) {
	var firstmatch = false;
	var reqarr = new Array();
	var testcontent = false;
	// Walk through all elements of the form
	for(var i=0;i<ref.elements.length;i++) {
		// look for CSS requirement classnames
		reqarr = ref.elements[i].className.match(/(form_notempty|form_email|form_integer|form_float|form_phone)/g);
		if(reqarr != null) {
			if(reqarr.length > 0) {
				// remove possible red marker
				ref.elements[i].className = ref.elements[i].className.replace(/([\s]?form_markred)/g, "");
				// find out what type the element is and where to get the content from
				var skiptest = false;
				switch(ref.elements[i].type) {
					case "text":
					case "textarea": testcontent = ref.elements[i].value;break;
					case "checkbox": {
						// test if the element is checked
						if(ref.elements[i].checked !== true) {
							// fail, mark
							skiptest = true;
						}
						break;
					}
					case "radio": {
						var namelements = document.getElementsByName(ref.elements[i].name);
						var eltest = false;
						// go through all radio-buttons and check if one of them is selected
						for(var n=0;n<namelements.length;n++) {
							if(namelements[n].checked === true) {
								// got one, break loop
								eltest = true;
								break;
							}
						}
						if(!eltest) {
							// else mark
							skiptest = true;
						}
						break;
					}
					default: testcontent = false;
				}
				// do required checks, based on classnames
				if(!skiptest && testcontent !== false) {
					var classerror = false;
					for(var z=0;z<reqarr.length;z++) {
						// validate string is not empty
						testcontent = testcontent.replace(/(^\s*)|(\s*$)/g, "");
						if(reqarr[z] === "form_notempty") {
							if(testcontent.length < 1) {
								classerror = true;
							}
						}
						// or select the proper regex-string for testing
						else {
							// Ignore string if it is empty (use "notempty" to check this)
							if(testcontent.length > 0) {
								// select the required regular expression
								var regexstring = new RegExp();
								switch(reqarr[z]) {
									case "form_email": regexstring = /^[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,6}$/i;break;
									case "form_integer": regexstring = /^\d+$/;break;
									case "form_float": regexstring = /^[-+]?[0-9]*\.?[0-9]+\b$/;break;
									case "form_phone": regexstring = /^[\-+]?[0-9\/\- ()]+$/;break;
								}
								// and test
								if(!regexstring.test(testcontent)) {
									classerror = true;
								}
							}
						}
						// kill loop on first match, ignore the rest
						if(classerror) {
							break;
						}
					}
				}
				if(skiptest || classerror) {
					// remember first match element, to focus later
					firstmatch = (!firstmatch) ? i : firstmatch;
					// mark the element
					ref.elements[i].className += " form_markred";
				}
			}
		}
	}
	if(firstmatch) {
		// mark the first match
		ref.elements[firstmatch].focus();
		return false;
	}
	return true;
}

// AJAX functions
if(window.XMLHttpRequest) {
	request = new XMLHttpRequest();
}
else if(window.ActiveXObject) {
	try {
		request = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e) {
		try {
			request = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch(e) {
			// no ajax support
		}
	}
}
// ]]>
