var isIE = navigator.userAgent.indexOf("MSIE") > -1
		&& navigator.userAgent.indexOf("Opera") == -1;
var isMoz = navigator.userAgent.indexOf('Mozilla/5.0') > -1
		&& !(navigator.userAgent.indexOf('WebKit') > -1);
var isIE8 = isIE && navigator.userAgent.indexOf("MSIE 8.0") > -1;

var HeightCorrector = 50;
var WidthCorrector = 6;

/**
 * extracts the uri of the current page
 */
function getURI()
{
	var loc = window.location + "";
	return loc.match(/(\/[^\/?#]+)+/)[0];
} 

/**
 * convenience function for executing remote action through ajax
 */
function executeRemoteAction(action, params, callback)
{
	var page_request;
	if (window.XMLHttpRequest) // if Mozilla, Safari, IE 7 etc
	{
		page_request = new XMLHttpRequest();
	}
	// if IE < 7
	else if (window.ActiveXObject)
	{ 
		try {
			page_request = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e)
		{
			try{
				page_request = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e){}
		}
	}
	else
		return false; // object could not be created (should not happen...)

	// set feedback function
	page_request.onreadystatechange=function() 
	{
		if (page_request.readyState == 4)
		{
			if(page_request.status != 200)
			{
				alert(page_request.statusText);
			}
			else
			if(callback)
			{
				callback(page_request.responseText);
			}
		}		
	}

	try
	{
		// get da bitch
		page_request.open('POST', "/RemoteActionProcessor/"+getURI()+"?RemoteAction_ID="+encodeURIComponent(action), true);
      	page_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      	page_request.setRequestHeader("Content-length", params.length);		
		page_request.send(params);
	}
	catch(e)
	{
		alert('<b>Error</b>: ' + e);
	}
}

/**
* convenience function for updating AjaxBlock
*/
function updateBlock(id, params, callback)
{
	if(params)
		params = "&"+params;
	else
		params = "";
	loadIntoElement("/AjaxContentDisplayer/"+getURI()+"?AjaxBlock_ID="+encodeURIComponent(id)+params, 
		document.getElementById(id), callback);
}

/**
 * load page from url into a html block element
 */
function loadIntoElement(url, block, callback)
{
	// defer displaying of loading information, so for very small ajax blocks we don't 
	// flash. but don't defer to much so loading information still appears to user instanous
	var timer = setTimeout("showLoading()", 200);

	var page_request;
	if (window.XMLHttpRequest) // if Mozilla, Safari, IE 7 etc
	{
		page_request = new XMLHttpRequest();
	}
	// if IE < 7
	else if (window.ActiveXObject)
	{ 
		try {
			page_request = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e)
		{
			try{
				page_request = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e){}
		}
	}
	else
		return false; // object could not be created (should not happen...)

	// set feedback function
	page_request.onreadystatechange=function()
	{
		if (page_request.readyState == 4)
		{
			var text = page_request.responseText;
			if(text && text.length > 0)
			{
				if(text.search(/^\s*eval\(.*\)\s*$/) > -1) // if text is like eval([javascript]), execute
					eval(text);
				else
					block.innerHTML = text;
			}
			else
				if(page_request.status != 200)
					block.innerHTML = page_request.statusText;
				else
					block.innerHTML = '';	

			clearTimeout(timer);
			hideLoading();
			if(callback)
				callback();
		}
	}

	// ensure correct mime type if possible (use text plain for best compatibility)
	if(page_request.overrideMimeType)
		page_request.overrideMimeType('text/plain');

	try
	{
		// get da bitch
		page_request.open('GET', url, true);
		page_request.send(null);
	}
	catch(e)
	{
		block.innerHTML = '<b>Error</b>: ' + e;
	}
}

// gets the inner width of a window
function GetInnerSize () {
	var x,y;
	if (self.innerHeight) // all except Explorer
	{
		x = self.innerWidth;
		y = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight)
		// Explorer 6 Strict Mode
	{
		x = document.documentElement.clientWidth;
		y = document.documentElement.clientHeight;
	}
	else if (document.body) // other Explorers
	{
		x = document.body.clientWidth;
		y = document.body.clientHeight;
	}
	return [x,y];
}

// resizes windows inner dimension 
function ResizeToInner (w, h) {
	if(isIE)
	{
		// make sure we have a final x/y value
		// pick one or the other windows value, not both
		var x = window.screenLeft || window.screenX;
		var y = window.screenTop || window.screenY;
		// for now, move the window to the top left
		// then resize to the maximum viewable dimension possible
		window.moveTo(0,0);
		window.resizeTo(screen.availWidth,screen.availHeight);
		// now that we have set the browser to it's biggest possible size
		// get the inner dimensions.  the offset is the difference.
		var inner = GetInnerSize();
		var ox = screen.availWidth-inner[0];
		var oy = screen.availHeight-inner[1];
		// now that we have an offset value, size the browser
		// and position it
		window.resizeTo(w+ox, h+oy);
		window.moveTo(x,y);
	}
	else
	{
		window.innerWidth = w;
		window.innerHeight = h;
	}
}

function RemoveSpaces(inp) {
	var buffer = '';
	for (z=0; z < inp.length; z++)
		if(inp.charAt(z) != ' ') buffer = buffer + inp.charAt(z);
	return buffer;
}

function ReplaceUndefined(inp,rep) {
 if(inp == 'undefined') inp = rep;
 return inp;
}

function generateCompanyLogin(CompanyName)
{ 
 var CompanyLogin = RemoveSpaces(CompanyName);

 if(CompanyLogin.length > 15) 
  CompanyLogin = CompanyLogin.substring(0, 15);
 
 return CompanyLogin.toLowerCase();
}

function setFocus(element)
{
 element.focus();
 if(element.select)
  element.select();
}

function PageLoaded()
{
 hideLoading();

 MM_preloadImages(
                  '/Images/AboutButton1.gif',
                  '/Images/MainButton1.gif',
                  '/Images/InfoButton1.gif',
                  '/Images/VereinButton1.gif',
                  '/Images/MemberButton1.gif',
                  '/Images/RegisterButton1.gif',
                  '/Images/HelpButton1.gif',
                  '/Images/DemoButton1.gif',
                  '/Images/ManualButton1.gif',
                  '/Images/PriceButton1.gif',
                  '/Images/DocumentationButton1.gif',
                  '/Images/ContactButton1.gif',


                  '/Images/MitgliederTRButton0.gif',
                  '/Images/TermineTRButton0.gif',
                  '/Images/MaterialTRButton0.gif',
                  '/Images/FinanzenTRButton0.gif',
                  '/Images/SystemTRButton0.gif',

                  '/Images/MitgliederTRButton1.gif',
                  '/Images/TermineTRButton1.gif',
                  '/Images/MaterialTRButton1.gif',
                  '/Images/FinanzenTRButton1.gif',
                  '/Images/SystemTRButton1.gif'
                 );

}

function hideLoading()
{
 document.body.style.cursor = 'auto';
 if(document.getElementById('Loading') != null)
  document.getElementById('Loading').style.visibility = 'hidden'; 
} 

function showLoading()
{
 if(document.getElementById('Loading') != null)
  document.getElementById('Loading').style.visibility = 'visible'; 
}

//focuses first text input element
function focusFirstTextinput(form)
{
	var els = document.forms[form].elements;
	if(els)
	{
		for(var i = 0; i < els.length; i++)
		{
			var el = els[i];
			if(el.type.toLowerCase() == 'text' || el.tagName.toLowerCase() == 'textarea')
			{
				setFocus(el);
				return;
			}
		}
	}
}


/**
 * Functions used by matcher.Results
 */

function resizeResultWindow()
{
 window.resizeTo(300, document.body.scrollHeight+40);
}

function openResultWindow(Page)
{
 var left = Math.round((window.screen.width-300)/2);
 var top  = Math.round((window.screen.height-400)/2);
 window.open(Page,'_blank','width=300,height=200,status=no,scrollbar=0,scrollbars=No,screenX='+left+',screenY='+top+',left='+left+',top='+top+',resizable=no');
 window.close(); 
}


/**
 * Functions used by DownloadWindow
 */
/* 
function resizeDownloadWindow()
{
 window.resizeTo(300, document.body.scrollHeight+40);
}

function doDownload(url)
{
 window.opener.location.replace(url);
 window.close();
}

function showDownload(Page)
{
 var left = Math.round((window.screen.width-300)/2);
 var top  = Math.round((window.screen.height-400)/2);
 window.open(Page,'DlWin','width=300,height=200,status=no,scrollbar=0,scrollbars=No,screenX='+left+',screenY='+top+',left='+left+',top='+top+',resizable=no');
}
*/
 /**
  * Functions used by DBTable
  */

 var AlterDirection = 0;
 var MaxRows = new Object();
 var TotalRows = new Object();
 var Position = new Object();

 function AlterMaxRows(tableID)
 {
 	var id;
 	if(!tableID) // backwards combat
 		id = "DBTable_PositionIndicator";
 	else
 		id = tableID+"_positionIndicator";

 	if(AlterDirection != 0
 			&& (AlterDirection > 0 || MaxRows[tableID] > 5)
 			&& Position[tableID]+MaxRows[tableID] < TotalRows[tableID])
 	{
 		MaxRows[tableID] += AlterDirection;

 		document.getElementById(id).innerHTML =
 			(Position[tableID]+1)+"-"+(Position[tableID]+MaxRows[tableID]);
 		if(tableID)
 			setTimeout("AlterMaxRows('"+tableID+"')", 140);
 		else
 			setTimeout("AlterMaxRows()", 140);
 	}
 }

 function AlterMaxRows_Start(tableID, direction)
 {
 	MaxRows[tableID] = parseInt(document.forms['DBTable_NavigationForm_'+tableID].DBTableNavigation_MaxRows.value);
 	TotalRows[tableID] = parseInt(document.forms['DBTable_NavigationForm_'+tableID].DBTableNavigation_TotalRows.value);
 	Position[tableID] = parseInt(document.forms['DBTable_NavigationForm_'+tableID].DBTableNavigation_Position.value);

 	AlterDirection = direction;
 	AlterMaxRows(tableID);
 }

 function AlterMaxRows_Finish(tableID)
 {
 	if(AlterDirection != 0)
 	{
 		AlterDirection = 0;

 		document.forms['DBTable_NavigationForm_'+tableID].DBTableNavigation_MaxRows.value = MaxRows[tableID];

 		if(tableID)
 		{
 			try
 			{
 				dbTableReload(document.forms['DBTable_NavigationForm_'+tableID], tableID);
 			}
 			catch (e)
 			{
 				// only submit form if ajax failed
 				showLoading();
 				document.forms['DBTable_NavigationForm_'+tableID].submit();
 			}
 		}
 		else
 		{
 			// for backward compatibility to old DBTable
 			showLoading();
 			document.forms['DBTable_NavigationForm_'+tableID].submit();	
 		}
 	}
 }

 // reloads dbtable either by ajax or normally
 function dbTableOrderByClick(tableID, el)
 {
 	var form = document.forms['DBTable_OrderByForm_'+tableID];
 	try
 	{
 		form.buttonClicked = el.name;
 		dbTableReload(form, tableID);
 	}
 	catch (e)
 	{
   	// only submit form if ajax failed
 		showLoading();
 		  var h=document.createElement('input');
 		  input.type = 'hidden';
 		  input.name = el.name+'.x';
 		  input.value = 'c';
 		form.appendChild(h);
 	  form.submit();
 	}
 }

 // reloads the dbtable using ajax scripting
 function dbTableReload(form, tableID)
 {
 	var params = form.buttonClicked+".x=c"
 	
 	// iterate through elements
 	for (var i=0; i < form.elements.length; i++) {
 	   var element = form.elements[i];
 	   params += "&"+element.name+"="+encodeURIComponent(element.value);
 	}		

 	// now load new table using block displayer
 	var table = document.getElementById(tableID);
 	loadIntoElement("/DBTableBrowser/"+getURI()+"?DBTable_ID="+tableID+"&"+params, 
 		table, function() { if(table.colNoStart) dbTableFixColumn(tableID); });
 	
 	return false;
 }

 function dbTableFixColumn(id, colNoStart) {
 	 
 	var containerDiv = document.getElementById(id);
 	if(colNoStart)
 	{
 		containerDiv.colNoStart = colNoStart
 	}
 	else
 		{
 			colNoStart = containerDiv.colNoStart;
 		}
 	
 	var containerTable = containerDiv.getElementsByTagName('table')[0];

 	var table = containerTable.getElementsByTagName('table')[0];

 	table.parentNode.style.height = (table.clientHeight + 22) + 'px';
 	table.parentNode.style.width = (table.clientWidth + 0) + 'px';
 	table.parentNode.style.maxWidth = '100%';

 	var fixedTable = table.cloneNode(false);

 	var rows = table.getElementsByTagName('tr');
 	// get max column count
 	var maxColno = 0;
 	for(var rowno = 0; rowno < rows.length; rowno++)
 	{
 		var row = rows[rowno];

 		var cols = row.childNodes;
 		var colno = 0;
 		for(var no = 0; no < cols.length; no++)
 		{
 			var col = cols[no];
 			if(col.tagName && (col.tagName.toLowerCase() == 'td' || col.tagName.toLowerCase() == 'th'))
 			{
 				colno += col.colSpan;
 			}
 		}
 		if(colno >= maxColno)
 			maxColno = colno;
 	}
 	
 	// iterate through table and move fixed columns to new table
 	var width = 0;
 	var heights = new Array();
 	for(var rowno = 0; rowno < rows.length; rowno++)
 	{
 		var row = rows[rowno];

 		var fixedRow = row.cloneNode(false);
 		fixedTable.appendChild(fixedRow);

 		var cols = row.childNodes;
 		var colno = 0;
 		var cwidth = 0; 
 		for(var no = 0; no < cols.length; no++)
 		{
 			var col = cols[no];
 			if(col.tagName && (col.tagName.toLowerCase() == 'td' || col.tagName.toLowerCase() == 'th'))
 			{
 				var paddingTop = col.style.paddingTop;
 				if(!paddingTop)
 					paddinTop = table.cellPadding;
 				if(!paddingTop)
 					paddinTop = 0;

 				var paddingBottom = col.style.paddingBottom;
 				if(!paddingBottom)
 					paddingBottom = table.cellPadding;
 				if(!paddingBottom)
 					paddingBottom = 0;
 					
 				if(table.cellSpacing && !isMoz) // we only need corrections for browsers != mozilla
 				{
 					paddingTop += table.cellSpacing;
 					paddingBottom += table.cellSpacing;
 				}

 				var height = col.clientHeight - paddingTop - paddingBottom;
 				heights[rowno] = height;

 				if(colno >= colNoStart)
 				{
 					cwidth += col.clientWidth;
 					
 					col.style.height = height + 'px';
 	
 					fixedRow.appendChild(col);
 				}

 				colno += col.colSpan;
 			}
 		}
 		if(cwidth > width)
 			width = cwidth;
 		// add additional invisible cols
 		while(colno < maxColno)
 		{
 			var col = document.createElement('td');
 			col.style.backgroundColor = 'white';
 			col.style.height = height + 'px';
 			col.innerHTML = '&nbsp;';
 			fixedRow.appendChild(col);
 			colno++;
 		}			
 	}
 	
 	for(var rowno = 0; rowno < rows.length; rowno++)
 	{
 		var row = rows[rowno];

 		var cols = row.childNodes;
 		var colno = 0;
 		for(var no = 0; no < cols.length; no++)
 		{
 			var col = cols[no];
 			if(col.tagName && (col.tagName.toLowerCase() == 'td' || col.tagName.toLowerCase() == 'th'))
 			{
 				col.style.height = heights[rowno]+'px';
 			}
 		}
 	}
 	
 	var cdiv = document.createElement('div');
 	cdiv.style.position = 'relative';
 	cdiv.style.left = 0;
 	cdiv.style.top = 0;
 	cdiv.style.right = 0;
 		
 	var tabdiv = document.createElement('div');
 	tabdiv.style.position = 'absolute';
 	tabdiv.style.overflowX = 'auto';
 	tabdiv.style.left = 0;
 	tabdiv.style.top = 0;
 	tabdiv.style.right = width + 'px';

 	tabdiv.style.border = 0;
 	tabdiv.style.padding = 0;
 	tabdiv.style.margin = 0;

 	var coldiv = document.createElement('div');
 	coldiv.style.position = 'absolute';
 	coldiv.style.right = 0;
 	coldiv.style.top = 0;
 	coldiv.style.width = width + 'px';
 	coldiv.style.overflow = 'hidden';
 	coldiv.style.textAlign = 'right';

 	coldiv.style.border = 0;
 	coldiv.style.padding = 0;
 	coldiv.style.margin = 0;

 	cdiv.appendChild(tabdiv);
 	cdiv.appendChild(coldiv);

 	table.parentNode.insertBefore(cdiv, table);

 	tabdiv.appendChild(table);
 	coldiv.appendChild(fixedTable);
 }


/*
 * Imported from Ultradev
 *
 */

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_findObj(n, d) { //v4.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}



/*
 * Functions for calendar
 */

function selected(cal, date) {
  cal.sel.value = date; // just update the date in the input field.
  cal.callCloseHandler();
}

function closeHandler(cal) {
  cal.hide();                        // hide the calendar
  cal.sel.focus();
}

function inputKey(input, event)
{
 if(event.keyCode == 32)
 {
  return showCalendar(input, input);
 } 
 else
  return true;
}

function showCalendar(button, el, format) 
{
  if (calendar == null) 
  {
    // first-time call, create the calendar.
    var cal = new Calendar(false, null, selected, closeHandler);
    // uncomment the following line to hide the week numbers
    // cal.weekNumbers = false;
    calendar = cal;                  // remember it in the global var
    cal.setRange(1900, 2070);        // min/max year allowed.
    cal.create();
    if (format != null)
     calendar.setDateFormat(format);  // set the specified date format
  }  

  calendar.parseDate(el.value);      // try to parse the text in field
  calendar.sel = el;                 // inform it what input field we use
  calendar.showAtElement(button);    // show the calendar below the button

  return false;
}
