function openBild(id, cmd)
{	
	var width = 540;
	if (cmd != 'Bild4')
	{
		width = 145
	}
	
	TextBoxModalDialog('frmBild.aspx?id=' + id + '&cmd=' + cmd, width, 167)
}

function openSorter(cmd, id)
{		
	TextBoxModalDialog('frmSorter.aspx?cmd=' + cmd + '&id=' + id, "640", "400")
}

function openReferenzVorschau(id)
{	
	OpenFormWidthHeightNoScroll('frmVorschau.aspx?id=' + id, 740, 575)
}


function openFrmUpload(id)
{			
	TextBoxModalDialog('frmUpload.aspx?id=' + id, 475, 300)
}


function openFrmTeilprojekteInvestition(IID)
{
	var url = "frmTeilprojekteInvestition.aspx"
	if (IID != '')
	{
		url = "frmTeilprojekteInvestition.aspx?id=" + IID
	}
			
	TextBoxModalDialog(url, 640, 400)
}


function openFrmProjektdetails(ProjektID)
{
	var url = "frmProjektdetails.aspx"
	
	if (ProjektID != '')
	{
		url = "frmProjektdetails.aspx?id=" + ProjektID
	}
			
	TextBoxModalDialog(url, 640, 400)
}


function openFrmProjekt(ProjektID, cmd)
{					
	OpenFormWidthHeightNoScrollAndID("frmProjekt.aspx?id=" + ProjektID + "&cmd=" + cmd, ProjektID, 660, 615)
}


function openReferenz(id)
{
	OpenFormWidthHeightNoScroll('Referenz.aspx?id=' + id, 740, 575)
}

/*
------------------------------------------------------------------------------------------------
*/

function TextBoxModalDialog(url, width, heigth) 
{
	window.showModalDialog(url, '', 'dialogWidth: ' + width + 'px; dialogHeight: ' + heigth + 'px; center: Yes; help: No; resizable: No; scroll: No; status: No;');
}

function OpenModalDialog(url)
{
	window.showModalDialog(url, "", "center:yes; status:no");
}

function OpenInvisibleWindow()
{
	window.open("about:blank", "InvisibleWindow", "left=10000;top=10000");
}

function CopySelfToOpener()
{
	if (opener)
	{
		window.document.body.onload = null;
		window.opener.document.body.innerHTML = window.document.body.innerHTML;
		window.close();
	}
}

function OpenForm(url)
{
	OpenFormWidth(url, window.screen.availWidth / 2);
}

function OpenFormWidth(url, width)
{
	OpenFormWidthHeight(url, width, (window.screen.availHeight * 3 / 4))
}

function OpenFormWidthNoScroll(url, width)
{
	OpenFormWidthHeightNoScroll(url, width, (window.screen.availHeight * 3 / 4))
}

function OpenFormHeight(url, height)
{
	OpenFormWidthHeight(url, window.screen.availWidth / 2, height);
}

function OpenFormHeightNoScroll(url, height)
{
	OpenFormWidthHeightNoScroll(url, window.screen.availWidth / 2, height);
}

function OpenFormWidthHeight(url, width, height)
{
	OpenFormWidthHeightAndReturnWindow(url, width, height);

}

function OpenFormWidthHeightAndReturnWindow(url, width, height)
{
	var left = (window.screen.availWidth - width) / 2;
	var top = (window.screen.availHeight - height) / 2;
	
	var iFirst = url.lastIndexOf("/");
	var iLast = url.indexOf(".");
	//var windowName = url.substring(iFirst + 1, iLast - 1);
	
	var newWindow =  window.open(url, "_blank", "height=" + height + ",width=" + width +
		",left=" + left + ",top=" + top +
		",location=no,menubar=no,status=no,toolbar=no,resizable=no,scrollbars=yes");
	if (newWindow != null) {
	newWindow.focus();}
	return newWindow;
}

function OpenFormWidthHeightNoScroll(url, width, height)
{
	var left = (window.screen.availWidth - width) / 2;
	var top = (window.screen.availHeight - height) / 2;
	
	var iFirst = url.lastIndexOf("/");
	var iLast = url.indexOf(".");
	//var windowName = url.substring(iFirst + 1, iLast - 1);
	
	var newWindow =  window.open(url, "_blank", "height=" + height + ",width=" + width +
		",left=" + left + ",top=" + top +
		",location=no,menubar=no,status=no,toolbar=no,resizable=no,scrollbars=no");
		if (newWindow != null)
			newWindow.focus();
}

function OpenFormWidthHeightNoScrollAndID(url, ID, width, height)
{
	var left = (window.screen.availWidth - width) / 2;
	var top = (window.screen.availHeight - height) / 2;
		
	var newWindow =  window.open(url, ID, "height=" + height + ",width=" + width +
		",left=" + left + ",top=" + top +
		",location=no,menubar=no,status=no,toolbar=no,resizable=no,scrollbars=no");
		if (newWindow != null)
			newWindow.focus();
}

function SwitchListItem(hiddenName, row, multiSelection)
{
	var hidden = document.forms(0).all(hiddenName);
	var selectedListItems = hidden.value.split(",");
	var found = false;
	var rows = document.getElementsByTagName("TR");
	for (var i = 0; i < selectedListItems.length; i++)
	{
		if (row.name == selectedListItems[i])
		{
			// remove me from array
			selectedListItems[i] = selectedListItems[selectedListItems.length - 1];
			// unselect row
			row.style.backgroundColor = "white";
			row.style.color = "black";
			found = true;
		}
		else if (selectedListItems[i].length > 0 && !multiSelection)
		{
			for (var j = 0; j < rows.length; j++)
			{
				if (rows[j].getAttribute("name") == selectedListItems[i])
				{
					rows[j].style.backgroundColor = "white";
					rows[j].style.color = "black";
					break;
				}
			}
		}
	}
	if (!multiSelection)
	{
		selectedListItems = new Array();
	}
	else if (found)
	{
		// Remove last element of the array
		selectedListItems.length--;
	}
	if (!found)
	{
		// select me
		row.style.backgroundColor = "#000080";
		row.style.color = "white";
		selectedListItems[selectedListItems.length] = row.name;
	}
	hidden.value = selectedListItems.join(",");
}

function SelectListItem(hiddenName, row, multiSelection)
{
	if (document.forms(0).all(hiddenName).value != row.name)
	{
		SwitchListItem(hiddenName, row, multiSelection);
	}
}

function SetEnableStateListButtons(hiddenName, row, multiSelection, editButtonName, deleteButtonName)
{
	SwitchListItem(hiddenName, row, multiSelection);
	var hidden = document.forms(0).all(hiddenName);
	var bIsSelectedItem = (hidden.value != "");
	var editButton = document.all(editButtonName);
	var deleteButton = document.all(deleteButtonName);
  if (editButton != null)
  {
    editButton.disabled = !bIsSelectedItem;
    var tobj = document.getElementById("IsEditButtonEnabled");
    editButton.src = bIsSelectedItem ? "Images/tbEdit.gif" : "Images/tbEditDisabled.gif";
    if (tobj) if (tobj.value == "false") 
    {
      editButton.disabled = true;
      editButton.src = "Images/tbEditDisabled.gif";
    }
  }
  if (deleteButton != null)
  {
    deleteButton.disabled = !bIsSelectedItem;
    var tobj = document.getElementById("IsDeleteButtonEnabled");
    deleteButton.src = bIsSelectedItem ? "Images/tbDelete.gif" : "Images/tbDeleteDisabled.gif";
    if (tobj) if (tobj.value == "false") 
    {
      deleteButton.disabled = true;
      deleteButton.src = "Images/tbDeleteDisabled.gif";
    }
  }
}

var iSetHeaderWidthsCount = 3;
function SetHeaderWidths(headerName, tableName)
{
	var headerRow = document.all(headerName);
	var gridTable = document.all(tableName);
	var isError = false;
	for (var i = headerRow.cells.length - 1; i >= 0; i--)
	{
		headerRow.cells[i].innerHTML = gridTable.rows[0].cells[i].innerHTML;
		for (var j = headerRow.cells[i].attributes.length - 1; j >= 0; j--)
		{
			try
			{
				headerRow.cells[i].noWrap = gridTable.rows[0].cells[i].noWrap;
				headerRow.cells[i].align = gridTable.rows[0].cells[i].align;
				gridTable.rows[0].cells[i].id = tableName + "_td" + i;
				headerRow.cells[i].style.setExpression("width", gridTable.rows[0].cells[i].id + ".offsetWidth");
			}
			catch (e)
			{
				isError = true;
			}
		}
	}
	if (isError && iSetHeaderWidthsCount > 0)
	{
		iSetHeaderWidthsCount--;
		window.setTimeout("SetHeaderWidths(\"" + headerName + "\",\"" + tableName + "\")", 300);
	}
}

function FocusToFirstInput()
{
	var inputs = document.getElementsByTagName("input");
	for (var i = 0; i < inputs.length; i++)
	{
		if (inputs[i].type == "text")
		{
			inputs[i].focus();
			//inputs[i].select();
			break;
		}
	}
}

var ThousandsDelimeter;
var DecimalDelimeter;

function GetOldValue(field)
{
	var oldValue = field.getAttribute("OldValue");
	if (oldValue != null)
	{
		return oldValue;
	}
	return field.defaultValue;
}

function SetOldValue(field)
{
	if (field.options != null)
	{
		field.setAttribute("OldValue", field.selectedIndex);
		return;
	}
	field.setAttribute("OldValue", field.value);
}

function IsNull(field)
{
	if (field.options != null)
	{
		return (field.selectedIndex == 0 && field.options[0].text.length == 0);
	}
	return field.value.length == 0;
}

function ToDouble(field)
{
	var oldValue = field.value;
	var newValue = oldValue.replace(ThousandsDelimeter, "");
	while (newValue != oldValue)
	{
		oldValue = newValue;
		newValue = oldValue.replace(ThousandsDelimeter, "");
	}
	return parseFloat(newValue.replace(DecimalDelimeter, "."));
}

function IsNotNumber(field)
{
	var dblValue = ToDouble(field);
	if (isNaN(dblValue))
	{
		return true;
	}
	FormatDouble(field, dblValue + "")
}

function FormatDouble(field, value)
{
	var dblValue = parseFloat(value);
  
  if (dblValue != dblValue)
	{
		dblValue = 0;
	}
	var sValue = parseInt(dblValue * 100 + (dblValue < 0 ? -0.5 : 0.5)) + "";
  
  if (sValue.substr(0,1)=="-")
  {
    sValue = sValue.substr(1, sValue.length - 1);
    while (sValue.length < 3)
	  {
      sValue = "0" + sValue;
	  }
    sValue = "-" + sValue;
  }  
  else
  {
    while (sValue.length < 3)
	  {
      sValue = "0" + sValue;
	  }
  }
  	
  var i = sValue.length - 2;
	var result = DecimalDelimeter + sValue.substr(i, 2);
    
	for (i -= 3; i > 0; i -= 3)
	{
		var result = ThousandsDelimeter + sValue.substr(i, 3) + result;
	}
  
	result = sValue.substr(0, 3 + i) + result;
  result = result.replace("-" + ThousandsDelimeter, "-");
  field.value = result;
}

function Undo(field)
{
	if (field.options != null)
	{
		field.selectedIndex = GetOldValue(field);
		return;
	}
	field.value = GetOldValue(field);
}

function FormatDate(date)
{
	var result = document.all("DateFormat").value.toLowerCase();
	result = result.replace("yyyy", date.getFullYear() + "");
	result = result.replace("yy", date.getFullYear() + "");
	result = result.replace("mm", ((date.getMonth() + 1 >= 10)?(date.getMonth() + 1):("0"+(date.getMonth() + 1))) + "");
	result = result.replace("dd", ((date.getDate() >= 10)?date.getDate():("0"+date.getDate())) + "");
	return result;
}

function GetFullYear(year) {
//    return (year + parseInt(century)) - ((year < cutoffyear) ? 0 : 100);
    return (year + parseInt(2000)) - ((year < 2029) ? 0 : 100);
}

function ToDate(value)
{
	var dateFormat = document.all("DateFormat").value.toLowerCase();
	dateFormat = dateFormat.replace("yyyy", "y");
	dateFormat = dateFormat.replace("yy", "y");
	dateFormat = dateFormat.replace("mm", "m");
	dateFormat = dateFormat.replace("dd", "d");
	var dateorder = "";
	for (var i = 0; i < dateFormat.length; i++)
	{
		var nextChar = dateFormat.substr(i, 1);
		if (nextChar == "y" || nextChar == "m" || nextChar == "d")
		{
			dateorder = dateorder + nextChar;
		}
	}

    var yearFirstExp = new RegExp("^\\s*((\\d{4})|(\\d{2}))([-./])(\\d{1,2})\\4(\\d{1,2})\\s*$");
    m = value.match(yearFirstExp);
    var day, month, year;
    if (m != null && (m[2].length == 4 || dateorder == "ymd")) {
        day = m[6];
        month = m[5];
        year = (m[2].length == 4) ? m[2] : GetFullYear(parseInt(m[3], 10))
    }
    else {
        if (dateorder == "ymd"){
            return null;		
        }						
        var yearLastExp = new RegExp("^\\s*(\\d{1,2})([-./])(\\d{1,2})\\2((\\d{4})|(\\d{2}))\\s*$");
        m = value.match(yearLastExp);
        if (m == null) {
            return null;
        }
        if (dateorder == "mdy") {
            day = m[3];
            month = m[1];
        }
        else {
            day = m[1];
            month = m[3];
        }
        year = (m[5].length == 4) ? m[5] : GetFullYear(parseInt(m[6], 10))
    }
    month -= 1;
    var date = new Date(year, month, day);
    return (typeof(date) == "object" && year == date.getFullYear() && month == date.getMonth() && day == date.getDate()) ? date.valueOf() : null;
}

function IsDate(value)
{
	return ToDate(value) != null;
}

function SaveLastFocus()
{
  if (document.getElementById("LACname"))
  {
    var objval = document.getElementById("LACname").value + "_LastActiveControl";
    if (document.getElementById(objval) && document.activeElement) document.getElementById(objval).value = document.activeElement.id;
  }
}

function SetOnFocusEvents()
{
  var inputs = document.getElementsByTagName("input");
  for (var i = 0; i < inputs.length; i++)
  {
    if (inputs[i].type == "text" && !inputs[i].readOnly)
    {
      inputs[i].onfocus = SaveLastFocus;
    }
  }
  var inputs = document.getElementsByTagName("textarea");
  for (var i = 0; i < inputs.length; i++)
  {
    if (!inputs[i].readOnly)
    {
      inputs[i].onfocus = SaveLastFocus;
    }
  }
}





function istZahl(str)
{
	var ausdruck=/^(\+|-)?(([1-9][0-9.]*\,?\d*)|(0?\,\d*)|0)$/;
	if (!str.match(ausdruck)) return false;
	return true;
}

function getFeldWert(field)
{
	if (field.value=="" || !istZahl(field.value)) return 0;
	return ToDouble(field);
}

function FormatAndSave(field,value)
{
	FormatDouble(field,value);
	field.oldvalue=field.value;//save value for undo
}


function gotonextbranch(n)
{
	while (n.nextSibling==null && n.parentNode!=null)
	{
		n=n.parentNode;			
	}
	if (n.parentNode==null) return null;
	n=n.nextSibling;
	if (n==null) return null;
	
	while (n.firstChild!=null) n=n.firstChild;
	return n;
}

//tries to find the next Element after the given that should recieve the focus, and focuses it.
//currently ignores the taborder and fails if <field> is the last element in the page
//only focuses on editable INPUT and TEXTAREA fields
function focusnext(field)
{
	var n=field;
	while (n!=null)
	{
		n=gotonextbranch(n);
		if (n.nodeName=="#text" || n.nodeName=="TD" || n.nodeName=="TR" || n.nodeName=="IMG") continue;
		if (n.nodeName=="INPUT" || n.nodeName=="TEXTAREA")
		{
			if (n.readOnly) continue;
			//alert(n.readOnly);
			n.focus();
			return;		
		}
		//alert("unknown nodename:"+n.nodeName);
		return;
	}
}

function afterClientFieldEdit(fieldname)
{
	var field=document.all(fieldname);
	if (!field) 
	{
		alert("ERROR: afterClientFieldEdit() unknown object '" + fieldname + "'");
		return true;
	}
	if (field.value=="") 
	{
		//nothing entered, write 0,00 and continue on.
		FormatAndSave(field,0);
		//nach 10ms den focus zum nächsten elemnt schieben.
		setTimeout("focusnext(document.all('"+field.name+"'));",10);

		return false;
	}
	else if( !istZahl(field.value) ) 
	{ 
		Undo(field);
		field.focus();
		field.oldvalue=field.value;
		return false;
	}

	FormatAndSave(field,ToDouble(field)); //correctly format it
	return true;
}

function generateOnChangeFunction(field,strtocall)
{
	field.onchange = new Function("var field=document.all('"+field.name+"');var r=afterClientFieldEdit(field.name);var val=getFeldWert(field);"+strtocall+";	return r && (val==getFeldWert(field));");
}
