﻿// ***********************************************************************************
// JScript functions for Formengine
// ***********************************************************************************
/// <reference path="jquery-1.4.1.js" />


// General
function SetField(pField,pValue)
{
	document.all.item(pField).value = pValue;
}

function __deleteItem(pTarget)
{
	if (window.confirm(msgDelete)) 
	{
		window.location.href = pTarget;
	}
}


// Editor.aspx ***********************************************************************
function sd(pItem,pImagePath)
{
	if (document.getElementById(pItem).style.display == "block")
	{
		document.getElementById(pItem).style.display = "none";
		document.getElementById("IMG_"+pItem).src = pImagePath + "i_cc.gif";
	}
	else
	{
		document.getElementById(pItem).style.display = "block";
		document.getElementById("IMG_"+pItem).src = pImagePath + "i_c.gif";
	}
}

function sdr(pItem,pImagePath,pHiddenField)
{
	if (document.all.item(pItem).style.display == "block")
	{
		document.all.item(pHiddenField).value = "none";
		document.all.item(pItem).style.display = "none";
		document.all.item("IMG_"+pItem).src = pImagePath + "ico_editor_admin_category_closed.gif";
	}
	else
	{
		document.all.item(pHiddenField).value = "block";
		document.all.item(pItem).style.display = "block";
		document.all.item("IMG_"+pItem).src = pImagePath + "ico_editor_admin_category.gif";
	}
}


function sdrx(pItem,pImagePath,pHiddenField,pCat)
{
	if (document.all.item(pItem).style.display == "block")
	{
		document.all.item(pHiddenField).value = pCat + "_0";
		document.all.item(pItem).style.display = "none";
		document.all.item("IMG_"+pItem).src = pImagePath + "ico_editor_admin_category_closed.gif";
	}
	else
	{
		document.all.item(pHiddenField).value = pCat + "_1";
		document.all.item(pItem).style.display = "block";
		document.all.item("IMG_"+pItem).src = pImagePath + "ico_editor_admin_category.gif";
	}
}

catArray = new Array();
function GetLink(pLinkbase,pSpot)
{	
	var ls = "";
	var c = 0;
	for (var i=0; i<catArray.length; i++)
	{
		if (c != 0)
		{
			ls += "x";
		}
		ls += document.all.item(catArray[i]).value;
		c++;
	}
	window.location.href = pLinkbase + "&tree=" + ls + pSpot;
	
}

function DeleteItem(pAsk,pLinkbase,pSpot)
{
	if (window.confirm(pAsk))
	{
		GetLink(pLinkbase,pSpot)
	}
}

function ome(pThis) // onmouseenter
{
	pThis.style.background='#FFFFFF';
}

function oml(pThis) // onmouseleave
{
	pThis.style.background="#EFEFEF";
}

function red(pModule)
{
	window.location.href = "Editor.aspx?select=" + pModule;
}


// Editor.aspx END ***********************************************************************




// Checklist ***********************************************************************
function CLCI(pItem, pStyleSet, pLast)//CheckListClickItem
{

	if (pLast == "True")
	{
		if (document.getElementById("h_"+ pItem).value == "True")
		{
			//document.getElementById(pItem).className = "c_cl_"+ pStyleSet +"_off";
			document.getElementById(pItem).style.background = "#efefef";
			document.getElementById("h_"+ pItem).value = "False";
		}
		else
		{
			//document.getElementById(pItem).className = "c_cl_"+ pStyleSet +"_on";
			document.getElementById(pItem).style.background = "#B5CBEB";
			document.getElementById("h_"+ pItem).value = "True";
		}
	}
	else
	{
		if (document.getElementById("h_"+ pItem).value == "True")
		{
			//document.getElementById(pItem).className = "c_cl_"+ pStyleSet +"_off_bb";
			document.getElementById(pItem).style.background = "#efefef";
			document.getElementById("h_"+ pItem).value = "False";
		}
		else
		{
			//document.getElementById(pItem).className = "c_cl_"+ pStyleSet +"_on_bb";
			document.getElementById(pItem).style.background = "#B5CBEB";
			document.getElementById("h_"+ pItem).value = "True";
		}
	}
}






// Checklist END ***********************************************************************






// PropertyRelationEditor ***********************************************************************

function PRD(pItem, pOpenImage, pClosedImage) // PropertyRelationDetail
{
	if (document.all.item("PropertyDetail"+ pItem).value == "False")
	{
		document.all.item("EditProperty"+ pItem).style.display = "block";
		document.all.item("PropertyDetail"+ pItem).value = "True";
		document.all.item("OpenImage"+ pItem).src = pOpenImage;
	}
	else
	{
		document.all.item("EditProperty"+ pItem).style.display = "none";
		document.all.item("PropertyDetail"+ pItem).value = "False";
		document.all.item("OpenImage"+ pItem).src = pClosedImage;
	}
}


function PRC(pItem) // PropertyRelationCount
{
	var count = 0;
	var lastCount = 0;
	var currentCount = 0;
	var begin = "<span class=c_pre_Editor_cb>";
	var end = "</span>";
	
	currentCount = document.all.item("PropertyRelationLastCounter").value;
	count = document.all.item("PropertyRelationCounterField").value;
	if (currentCount > 0)
	{
		count = currentCount;
		document.all.item("PropertyRelationLastCounter").value = 0;
	}

	document.all.item("PropertyRelationCounterField").value = count;

	count++;
	document.all.item("PropertyRelationCounterField").value = count;
	document.all.item("SortOrderCounter"+ pItem).innerHTML = begin + count + end;
	document.all.item("3_"+ pItem).value = count;
	
}

function PLC(pCount) // PropertySetLastCount
{
	var lastCount = 0;
	lastCount = document.all.item("PropertyRelationLastCounter").value;
	if (pCount > lastCount)
	{
		document.all.item("PropertyRelationLastCounter").value = pCount;
	}
}


function PSF(pItem) // PropertyRelationCountSetFirst
{
	var count = 1;
	var begin = "<span class=c_pre_Editor_cb>";
	var end = "</span>";

	document.all.item("PropertyRelationLastCounter").value = count;
	document.all.item("PropertyRelationCounterField").value = count;
	document.all.item("SortOrderCounter"+ pItem).innerHTML = begin + count + end;
	document.all.item("3_"+ pItem).value = count;
}

function RCS(pItem,pCount) // PropertyRelationCountSetSpecific
{
	var count = 0;
	if (pCount > 0)
	{
		count = pCount;
	}
	var begin = "<span class=c_pre_Editor_cb>";
	var end = "</span>";

	document.all.item("PropertyRelationCounterField").value = count;
	document.all.item("SortOrderCounter"+ pItem).innerHTML = begin + count + end;
	document.all.item("3_"+ pItem).value = count;
}




			
var AddImageUrl= "";
var RemoveImageUrl="";

function RPRCh(pID) // Changed PropertyRelation
{

	if(AddImageUrl == "")
		AddImageUrl = document.getElementById("EditPropertyAddImageUrl").value;
	
	if(RemoveImageUrl == "")
		RemoveImageUrl = document.getElementById("EditPropertyRemoveImageUrl").value;
		
	
	var OldPropertyRelations = document.getElementById("EditedPropertyRelations").value;
	if (OldPropertyRelations.indexOf(';'+pID+';')< 0) //CreateNewPropertyRelation
	{
		document.getElementById("EditedPropertyRelations").value = document.getElementById("EditedPropertyRelations").value + pID + ';';
		document.getElementById('PRT'+pID).attributes['class'].value = 'c_pre_Editor_on_bb'
		document.getElementById('PRImg'+pID).attributes['src'].value = RemoveImageUrl;
	}
	else //RemovePropertyRelation
	{
		if (window.confirm('Do you really want to remove this relation?'))
		{			
			document.getElementById("EditedPropertyRelations").value = OldPropertyRelations.replace(';'+pID+';',';');	
			document.getElementById('PRT'+pID).attributes['class'].value = 'c_pre_Editor_off_bb'
			document.getElementById('PRImg'+pID).attributes['src'].value = AddImageUrl;
		}
	}		
}


function PL(pID) // PropertyLink
{
	window.open("AdministrationDialog.aspx?select=14&item="+pID+"&act=1#spot");
}

// PropertyRelationEditor END ***********************************************************************




// TemplateEditor ***************************************************************************


var restrictoutput = false;

function ip(iproperty,ixmlproperty) // Insert Property
{
	if (restrictoutput != true)
	{
		var insertProperty = "";
		var name = document.getElementsByName("TE_select_Name")[0].value;
		var titlename = document.getElementsByName("TE_title_Name")[0].value;
		var bodyname = document.getElementsByName("TE_body_Name")[0].value;
		var temptypename = document.getElementsByName("TE_temp_Type")[0].value;
		var temptype;
		
		if (temptypename!="")
		    temptype = document.getElementById(temptypename).value;
		
		
		var target = document.getElementsByName(document.getElementsByName(name)[0].value)[0]; //forms[0].elements[document.all.item(name).value]
		var sel = document.selection;		
		
		insertProperty = iproperty;
		
		switch (temptype)
		{
			case "html":
				break;
			case "activecontent":
				break;
			case "xslt":
			    if (document.getElementById(name).value == bodyname)
				{
					insertProperty = ixmlproperty;
				}
				break;
			case "renderclass":
				break;
		}


		if (sel != null) {


		    var rng = sel.createRange();
		    var oRng1 = document.body.createTextRange();
		    oRng1.moveToElementText(target);
		    if (rng != null) {
		        if (oRng1.inRange(rng)) {
		            rng.text = insertProperty;
		        }
		        else {
		            //alert("not in range[" + rng.text +"]");
		            oRng1.text = oRng1.text + insertProperty;
		        }

		    }
		    else {
		        //alert('range null');
		        oRng1.text = oRng1.text + insertProperty;
		    }
		}
		else {
		    target = document.getElementById('TE_TETemplates_body');
		    
		    target.value = target.value + insertProperty;
		}
	}
}



function ipt(pStartTag,pEndTag) // Insert TAG
{
	var rangeTop = 0;
	var rangeLeft = 0;
	var rangeRight = 0;
	var rangeBottom = 0;
	if (restrictoutput != true)
	{
		var name = document.all.item("TE_select_Name").value;
		var target = document.forms[0].elements(document.all.item(name).value)
		var sel = document.selection;		
		if (sel!=null)			
		{	
			var rng = sel.createRange();
			var oRng1 = document.body.createTextRange();
			oRng1.moveToElementText(target);

			if (rng!=null) 
			{	
				/*
				rangeTop = rng.boundingTop;
				rangeLeft = rng.boundingLeft;
				rangeRight = (rng.boundingLeft + rng.boundingWidth);
				rangeBottom = (rng.boundingTop + rng.boundingHeight);
				*/

				if (oRng1.inRange(rng))
				{
					 rng.text = pStartTag + rng.text + pEndTag;
				}
				else
				{
					//alert("not in range, [" + rangeTop + ", "+ rangeLeft +", "+ rangeRight +", "+ rangeBottom +"]");
					oRng1.text = oRng1.text + pStartTag + " " + pEndTag;
				}
				
			}
			else
			{
				//alert('range null');
				oRng1.text = oRng1.text + pStartTag + " " + pEndTag;
			}
		}
	}
}

function clickIsTempSelect()
{
	document.forms[0].submit();
}

function HideShowPropCat(hiddVal)
{
	if (document.getElementById("CatProp_PRProperties_" + hiddVal).value == "False")
	{
		document.getElementById("hide_show_PRProperties_" + hiddVal).style.display = "block";
		document.getElementById("CatProp_PRProperties_" + hiddVal).value = "True";
	}
	else
	{
		document.getElementById("hide_show_PRProperties_" + hiddVal).style.display = "none";
		document.getElementById("CatProp_PRProperties_" + hiddVal).value = "False";
	}
}

function toce(pType) // onchange event select template types
{
	var name = document.all.item("TE_select_Name").value;
	var renderername = document.all.item("TE_renderer_Name").value;
	
	switch (pType)
	{
		case  "html":
			document.all.item(renderername).value = 14;
			document.all.item("HTML_tb_" + name).style.display = "block";
			document.all.item("STATIC_tb_" + name).style.display = "block";
			document.all.item("XSLT_tb_" + name).style.display = "none";
			document.all.item("ACL_tb_" + name).style.display = "none";
			document.all.item("FD_tb_"+ name).style.display = "none";
			document.all.item("RCL_tb_" + name).style.display = "none";
			document.all.item("textareadiv_TE_TETemplates_body").style.display = "block";
			break;
		case "activecontent":
			document.all.item(renderername).value = 15;
			document.all.item("HTML_tb_" + name).style.display = "block";
			document.all.item("STATIC_tb_" + name).style.display = "block";
			document.all.item("XSLT_tb_" + name).style.display = "none";
			document.all.item("ACL_tb_" + name).style.display = "block";
			document.all.item("FD_tb_"+ name).style.display = "none";
			document.all.item("RCL_tb_" + name).style.display = "none";
			//document.all.item("textareadiv_TE_TETemplates_body").style.display = "none";
			document.all.item("textareadiv_TE_TETemplates_body").style.display = "block";	
			break;
		case "xslt":
			document.all.item(renderername).value = 23;
			document.all.item("HTML_tb_" + name).style.display = "block";
			document.all.item("STATIC_tb_" + name).style.display = "block";
			document.all.item("XSLT_tb_" + name).style.display = "block";
			document.all.item("ACL_tb_" + name).style.display = "none";
			document.all.item("FD_tb_"+ name).style.display = "none";
			document.all.item("RCL_tb_" + name).style.display = "none";
			document.all.item("textareadiv_TE_TETemplates_body").style.display = "block";
			break;
		case "formdisplay":
			document.all.item(renderername).value = 98;
			document.all.item("HTML_tb_" + name).style.display = "block";
			document.all.item("STATIC_tb_" + name).style.display = "block";
			document.all.item("XSLT_tb_" + name).style.display = "none";
			document.all.item("ACL_tb_" + name).style.display = "none";
			document.all.item("FD_tb_"+ name).style.display = "block";
			document.all.item("RCL_tb_" + name).style.display = "none";
			document.all.item("textareadiv_TE_TETemplates_body").style.display = "block";			
			//document.all.item("textareadiv_TE_TETemplates_body").style.display = "none";
			break;
		default:
			document.all.item("HTML_tb_" + name).style.display = "block";
			document.all.item("STATIC_tb_" + name).style.display = "block";
			document.all.item("XSLT_tb_" + name).style.display = "none";
			document.all.item("ACL_tb_" + name).style.display = "none";
			document.all.item("FD_tb_"+ name).style.display = "none";
			document.all.item("RCL_tb_" + name).style.display = "block";
			//document.all.item("textareadiv_TE_TETemplates_body").style.display = "none";
			document.all.item("textareadiv_TE_TETemplates_body").style.display = "block";	
			break;
	}
}

function aoce(pValue)
{
	var bodyname = document.all.item("TE_body_Name").value;
	document.all.item(bodyname).value = pValue;
}

function roce(pRenderer) // onchange event select renderer classes
{
	var renderername = document.all.item("TE_renderer_Name").value;
	if (pRenderer > 0)
	{
		//alert(pRenderer);
		document.all.item(renderername).value = pRenderer;
	}
	/*
	else
	{
		alert(pRenderer);
	}
	*/
}


// TemplateEditor END ***********************************************************************

window.setTimeout('InitResizeHandlers()',50);

function InitResizeHandlers()
{
		if (document.body)
		{
			document.body.onmousemove=move; 
			document.body.onmouseup=mouseup;
		}
		else
			window.setTimeout('InitResizeHandlers()',2000);
}

var curSizeValue=0;
var resizeRequestPendingTarget=null;

function resizeImgWidth()
{
	
	var re=/&width=[0123456789]*/i;
	if (new String(resizeRequestPendingTarget.src).search(re)>=0)
	{
		resizeRequestPendingTarget.src=new String(resizeRequestPendingTarget.src).replace(re, '') + '&width=' + new String(resizeRequestPendingTarget.width);
	}
	resizeRequestPendingTarget=null;
}

function resizeImgHeight()
{
	
	var re=/&height=[0123456789]*/i;
	
	if (new String(resizeRequestPendingTarget.src).search(re)>=0)
	{
		resizeRequestPendingTarget.src=new String(resizeRequestPendingTarget.src).replace(re, '') + '&height=' + new String(resizeRequestPendingTarget.height);
	}
	
	resizeRequestPendingTarget=null;
}
function move(ev)
{

	ev = ev || window.event;
	if (timer!=0 && (timerx!=ev.clientX || timery!=ev.clientY))
	{
		window.clearTimeout(timer);
		timer=0;		
	}	
	if (resizeMode==true)
	{
	
		if (resizeDim=='width' || resizeDim=='both')
		{
			if (ev.pageX)			
				curSizeValue=ev.pageX-tdStartX;				
			else
				curSizeValue=window.event.clientX-tdStartX;
			if (curSizeValue>0)
			{
				oelem.width=curSizeValue;
				if (oelem.tagName=='IMG')
				{
					if (resizeRequestPendingTarget==null)
					{
						resizeRequestPendingTarget=oelem;
						window.setTimeout('resizeImgWidth()', 1000);
					}
				}
				if (oelem.style)
					oelem.style.width=curSizeValue;
				
			}
			window.status=curSizeValue;
		}
		if (resizeDim=='height' || resizeDim=='' || resizeDim=='both')
		{
			if (ev.pageY)
				curSizeValue=ev.pageY-tdStartY-10;
			else
				curSizeValue=window.event.clientY-tdStartY;
			if (curSizeValue>0)
			{
				oelem.height=curSizeValue;		
				if (oelem.tagName=='IMG')
				{
				
					if (resizeRequestPendingTarget==null)
					{
						resizeRequestPendingTarget=oelem;
						window.setTimeout('resizeImgHeight()', 1000);
					}
				}	
				if (oelem.style)
					oelem.style.height=curSizeValue;
			}
			window.status=curSizeValue;
		}
	}
		
	
	return true;
}

var resizeDim='width';
var timer;
var timerx, timery;

function mouseup()
{
	if (timer!=0)
	{
		window.clearTimeout(timer);
		timer=0;		
		window.status='';
	}
	if (resizeMode==true && DragDropEnabled && clientResize!='ClientOnly')
	{
		resizeMode=false;
		if (document.body.releaseCapture)
			document.body.releaseCapture();
		var url=strCallBack + '&s_resizeElement=true&s_PropertyId=' + propertyID + '&s_ElementId=' + resizeElementID + '&s_width=';
		//if (resizeDim=='width')
		//	execASP(url + oelem.width+'#show_'+ resizeElementID);
		//else
			execASP(url + curSizeValue +'#show_'+ resizeElementID);
	}
	if (resizeMode==true && DragDropEnabled && clientResize=='ClientOnly')
	{
		resizeMode=false;
		resizeDim='';
		if (document.body.releaseCapture)
			document.body.releaseCapture();
	}
}

var DragDropEnabled=true;
var tdStartX;
var tdStartY;

var clientResize='';
var oelem;
var resizeMode;
resizeMode=false;

function ResizeElementClient(element, dimension, ev)
{
		ev=ev || window.event;
		resizeMode=true;
		resizeDim=dimension;
		clientResize='ClientOnly';		
		if (document.body.setCapture)
			document.body.setCapture();
		if (ev.cancelBubble)
			ev.cancelBubble=true;
		oelem=element;	
		if (ev.pageX)
		{		
			tdStartX=ev.pageX-oelem.scrollWidth+20;
			tdStartY=ev.pageY-oelem.scrollHeight+20;
		}
		else
		{
			tdStartX=ev.clientX-oelem.scrollWidth;
			tdStartY=ev.clientY-oelem.scrollHeight;
		}
		return false;
}

function SelectMediaElement(val, valPath,dontSubmit)
{
	if(opener && opener.document && opener.document.forms[0] && opener.document.getElementsByName(window.name)[0])
	{
	
		//opener.onbeforeunload=null;
		if(window.name.indexOf("prop_")==0)
		{
		
			opener.document.getElementsByName(window.name)[0].value=opener.document.getElementsByName(window.name)[0].value + '<img  border="0" src="' + valPath +'">';opener.document.forms[0].submit();window.close();
		}
		else
		{
			opener.document.getElementsByName(window.name)[0].value=val;
			if(!dontSubmit)
			{
				opener.document.forms[0].submit();
			}
			window.close();
		}
	}
	else if (window.frameElement)
	{
		parent.document.getElementsByName(window.frameElement.getAttribute('targetField'))[0].value=val;parent.document.forms[0].submit();
	}
}


function Search(Url, SearchText)
{
	window.location.href=Url +'searchText=' + SearchText;
}

function EMail(Url, EMailText)
{
	window.location.href=Url +'emailText=' + EMailText;
}
/* Checklist_Toggle */
function cl_T(me, field, itemID)
{
	if (document.all[field].value=='')
		document.all[field].value=';';
	
	var curVal=new String(document.all[field].value);
	
	var re = new RegExp(";"+ itemID +";","i");

	if (curVal.search(re)!=-1)
	{
		document.all[field].value=curVal.replace(re,';');
		me.style.background = "#EFEFEF";
	}
	else
	{
		me.style.background = "#B5CBEB";
		document.all[field].value+= itemID + ';';
	}
	return false;
}

var AEListMultiSelectionToggleEvents = new Array(); // ElementID, IsChecked

function ToggleCheck(imgTag, elementID, usePostback, useViewState, windowID) {
	var srcpath=new String(imgTag.src);
	
	if (!useViewState)
	{
		useViewState=CurrentAppViewStateID;
		
	}
	
	var oldCount=CurrentSelectionCounter[useViewState];

	var url = AppRootPath + '/Kontext/WebService/ToggleListItem.aspx?avs=' + useViewState + '&ID=' + elementID;
	
	var result='';

	if (window.ActiveXObject) {
	    var xml2 = new ActiveXObject("Msxml2.DOMDocument");

	    xml2.async = false;
	    xml2.validateOnParse = false;
	    xml2.load(url);
	    result = xml2.text;
	    xml2 = null;

	}
	else if (window.XMLHttpRequest) {
	    var xmlhttp = null;
	    xmlhttp = new XMLHttpRequest();
	    xmlhttp.open("GET", url, false);
	    xmlhttp.send(null);
	    result = xmlhttp.responseText.replace('<val>','').replace('</val>', '');
	}

	var IsChecked = null;
	if (srcpath.indexOf("checkbox_inaktiv") >= 0) {
	    imgTag.src = srcpath.replace("checkbox_inaktiv", result);
	    if (result == "checkbox_aktiv") {
	        CurrentSelectionCounter[useViewState]++;
	        IsChecked = true;
	    }
	}
	else {
	    imgTag.src = srcpath.replace("checkbox_aktiv", result);
	    if (result == "checkbox_inaktiv") {
	        CurrentSelectionCounter[useViewState]--;
	        IsChecked = false;
	    }
	}
	if (IsChecked != null && AEListMultiSelectionToggleEvents.length > 0) {
	    for (var i = 0; i < AEListMultiSelectionToggleEvents.length; i++) {
	        AEListMultiSelectionToggleEvents[i](elementID, IsChecked);
	    }
	
	}
	
	
	//if (windowID=='' || !windowID)
	{
		if (document.getElementById('selection_count_' + useViewState))
		{
			document.getElementById('selection_count_' + useViewState).innerHTML=CurrentSelectionCounter[useViewState];
		
		}
	}

	var appFrame = document.getElementById('application_frame_' + useViewState);
	if (appFrame != null) {
	    if (CurrentSelectionCounter[useViewState] > 0)
	        appFrame.className = 'MultiSelActive';
	    else
	        appFrame.className = 'MultiSelInactive';
	    return;
	}
	
	if (oldCount==0 || CurrentSelectionCounter[useViewState]==0 /*|| (windowID && windowID!='')*/)
	{
	    if (usePostback) {
	        window.setTimeout('document.forms[0].submit()', 50);
	    }
	    else {
	        var targeturl = new String(location.href);
	        targeturl = targeturl.replace('&selectionMode=true', '');
	        targeturl = targeturl.replace('&mode=form', '');
	        if (window.navigate)
	            window.setTimeout('window.navigate("' + targeturl + '")', 50);
	        else
	            window.setTimeout('window.location.href ="' + targeturl + '";', 50);

	    }
	}
}

function markText(textVal, color)
{
  if (document.body.createTextRange)
  {
	var oRange = document.body.createTextRange();
	oRange.collapse();
	var first=true;
	while (oRange.move("word", 1))
	{
		if (first)
		{
			first=false;
			oRange.move("word",-1);
		}
		oRange.expand("word");
		if(oRange.findText(textVal))
		{
			oRange.execCommand('BackColor', "false", color);
		}

	}
  }
}

var timeoutset=false;

function validateFieldLength(control, maxlen, strMsg, ev) {

    ev = ev || window.event;
    var currentLength = 0;
    if (control.innerText)
        currentLength = control.innerText.length;
    else 
        currentLength = control.value.length;
    window.status = currentLength + '/' + maxlen;
	if (!timeoutset)
	{
		timeoutset=true;
		window.setTimeout('window.status="";timeoutset=false', 2000);
	}

	
	var counterAreaSpan = document.getElementById(control.attributes["id"].value + "_textspan");
	var counterSpan = document.getElementById(control.attributes["id"].value + "_number");
	if (counterAreaSpan && counterSpan) {
	    counterAreaSpan.style.display = "inline";
	   
	    counterSpan.innerHTML = currentLength;		
	}

	if (currentLength > maxlen && ev.keyCode != 8 && ev.keyCode != 46 && ev.keyCode != 37 && ev.keyCode != 39)
	{
		var re='%1';
		strng=new String(strMsg);
		var txt = strng.replace(re, currentLength);		
		window.alert(txt);
	}
	
	
	
}

var submitting=false;

function SetSubmit(control, ev)
{

	ev = ev || window.event;
	if(ev.keyCode==13) { 
		
		if (document.all)
		{
			if (window.document.getElementById("EnterSubmitField"))		
				window.document.getElementById("EnterSubmitField").value = control.name;
		}
		else
		{
			window.document.getElementsByName("EnterSubmitField").item(0).value = control.name;
			
		}			
		window.returnValue = false;	
		if (submitting)
			return false;
			
		submitting=true;		
		document.forms[0].submit();
		return false;
	}
}


function SwitchSetTab(pActiveTab, pAlign, pCssClassBase, pArray,ControlID)
{
	var i;
	var h;
	var j;
	var k=pArray.length;
	for (i=0;i<pArray.length;i++)
	{
		h = (i-1);
		j = (i+1);
		if (pActiveTab==pArray[i])
		{
			if (h != -1)
			{
				document.getElementById("SEP_" + pArray[h]).className = pCssClassBase+"_border_transparent";
			}
			document.getElementById(pArray[i]).style.display = "block";
			document.getElementById("SEP_" + pArray[i]).className = pCssClassBase+"_border_transparent";
			document.getElementById("DIV_" + pArray[i]).className = pCssClassBase+"_"+pAlign+"_border_on";
			document.getElementById("TAB_" + pArray[i]).className = pCssClassBase+"_on";
			
			document.getElementsByName(ControlID+'_activetab').item(0).value = i+1;
		}
		else
		{
			if (document.getElementById("TAB_" + pArray[i]).className == pCssClassBase+"_on");
			{
				document.getElementById("SEP_" + pArray[i]).className = pCssClassBase+"_border_color";
				document.getElementById("DIV_" + pArray[i]).className = pCssClassBase+"_"+pAlign+"_border_off";
				document.getElementById("TAB_" + pArray[i]).className = pCssClassBase+"_off";
			document.getElementById(pArray[i]).style.display = "none";
			}
		}

	}
}

function PlaceContent(content)
{
	document.writeln(content);
}

function SetIFrameSrcFromMemory(iframe)
{
	if(iframe.src == "" || iframe.src.indexOf('javascript') != -1)
	{
		iframe.src = iframe.getAttribute("srcmemory");
	}
}

function OpenOutlookItem(EntryID)
{
	try
	{
		var oOutlook = new ActiveXObject("Outlook.Application");
		var objNamespace = oOutlook.GetNamespace("MAPI");
		var objItem = objNamespace.GetItemFromID(EntryID,"");
		objItem.Display(null);
	}
	catch(err)
	{
		window.alert("Um Outlook-Objekte öffnen zu können, muss die Seite zu den vertrauenswürdigen Seiten hinzugefügt werden und das ActiveX-Control muss zugelassen werden.");
	}
}


var popupCounter=1;
function ShowIFrame(targetObject, url, ev)
{

    if (ev) {

        if (ev.stopPropagation) {
            ev.stopPropagation();
        }
        if (ev.preventBubble)
            ev.preventBubble(); 
        if (ev.preventDefault)
            ev.preventDefault();
        var r = document.createRange();
        r.setStartBefore(document.body);

        var parsedHTML = r.createContextualFragment('<iframe onLoad="AutoResizeIFrame(this)" style="position:absolute;width:150;height:100;left:' + ev.clientX + 'px;top:' + ev.clientY + 'px;z-index:' + popupCounter + '" src="' + url + ' ">');
        document.body.insertBefore(parsedHTML, document.body.firstChild);
         
        
        popupCounter++;
        return false;
    }
    else {

        var ev = ev || window.event;
        popupCounter++;
        document.body.insertAdjacentHTML('afterBegin', '<iframe onLoad="AutoResizeIFrame(this)" style="position:absolute;width:150;height:100;left:' + ev.x + 'px;top:' + ev.y + 'px;z-index:' + popupCounter + '" src="' + url + ' ">');
    }
	//window.open(url);
}

function AutoResizeIFrame(frame)
{
  var the_height= frame.contentWindow.document.body.scrollHeight;
  frame.style.height= the_height+20;  
  var the_width= frame.contentWindow.document.body.scrollWidth;
  frame.style.width= the_width+20;
}


function ResetTextboxValue(TextBoxID, NewValue)
{
	var TextBox = document.getElementById(TextBoxID);
	//alert(TextBoxID);
	TextBox.value = NewValue;	
}

function getAsyncRequest()
{
	var request=null;

	if (window.XMLHttpRequest)
    {    // Firefox, Opera 8.0+, Safari 1.2, IE 5.0+, Netscape 7
        request=new XMLHttpRequest();
    }
	
	if (request==null && window.ActiveXObject)
    {    // Internet Explorer
		try
		{
            request=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			try
			{
				request=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e)
			{
				alert('kein ajax');
				return false;
			}
		}
	}
	return request;
}

function updateDependency(parentEditor,dependentEditor,formFieldID,editorType)
{
	var request = getAsyncRequest();
	
	request.onreadystatechange = function() 
	{
		if(request.readyState == 4)
		{
			var depEd  = document.getElementsByName(dependentEditor);
			if(depEd)
			{			
				processCallback(request.responseXML, depEd[0], editorType, request);
			}
			else
			{
				alert('editor not found!');
			}
		}
	};
	
	
	request.open("GET",strCallbackUrl +"/kontext/webservice/formdata.aspx?formfieldid="+formFieldID + "&value="+parentEditor.value,true);	
	request.send(null);
}

function clearDDL(list)
{
	while(list.length > 0)
	{
		list.remove(0);
	}
}

function processCallback(xml, dependentElement, editorType, request)
{
	//alert('test');
	//alert('trying to change list: ' + dependentElement.name);

	switch(editorType)
	{
		case "DropDownList":
		case "ListBox":
			
			
			clearDDL(dependentElement);

			var option;

			if(editorType == "DropDownList")
			{
				option = new Option("","",false,false)//document.createElement("option");
				dependentElement.options[dependentElement.length] = option;
			}

			var optionArray = xml.getElementsByTagName("option");


			for(i=0; i<optionArray.length; i++)
			{
				var val = optionArray[i].attributes.getNamedItem("value").nodeValue;
			
				
				var txt;
				if (optionArray[i].childNodes[0] && optionArray[i].childNodes[0].nodeValue)
				{
					txt=optionArray[i].childNodes[0].nodeValue;
				
			
					option = new Option(txt,val,false,false); //document.createElement("option");
				
					dependentElement.options[dependentElement.length] = option;
				}
			}	
			
			break;
			
		case "":
			break;
	}
}

function clrEds(list)
{
	var eds = list.split("|");

	for(i=0; i < eds.length; i++)
	{
		var ed = document.getElementsByName(eds[i]);
		if(ed)
		{
			clearDDL(ed[0]);
		}
	}
}

function SetBoolValue(cb, idfield, elementID, propertyid)
{
    
	var useViewState=document.getElementsByName(idfield)[0].value;
	
	var url=AppRootPath + '/Kontext/WebService/AjaxBoolValueSetter.aspx?avs=' + useViewState + '&ElementID=' + elementID   + '&PropertyID=' + propertyid + '&newVal=' + cb.checked;
	
if (window.ActiveXObject)
  {
    var xml2 = new ActiveXObject("Msxml2.DOMDocument");
	
	xml2.async=true;
	xml2.validateOnParse=false;
	xml2.load(url);
	xml2=null;
	
  } 
else if (window.XMLHttpRequest)
  {
	var xmlhttp=null;  
    xmlhttp=new XMLHttpRequest();
    xmlhttp.open("GET", url, true);         
    xmlhttp.send(null);
  }
   
}

var filterbuffer='';
function ApplyFilter(listbox, ev)
{
    var ev=ev || window.event ;
     
       
    if (ev.keyCode==27 || ev.keyCode==8)
        filterbuffer='';
   
   

    
    if ((ev.keyCode>=65 && ev.keyCode<=90) || (ev.keyCode>=48 && ev.keyCode<=57) || ev.keyCode==32 || ev.keyCode==189 || ev.keyCode==190  || ev.keyCode==222  || ev.keyCode==192  || ev.keyCode==186   || ev.keyCode==219)
    {
       
       var character=String.fromCharCode(ev.keyCode);
       
       if (ev.keyCode==190)
        character='.';
       if (ev.keyCode==189)
        character='-';
        if (ev.keyCode==222)
            character='ä';
        if (ev.keyCode==192)
            character='ö';
        if (ev.keyCode==186)
            character='ü';
        if (ev.keyCode==219)
            character='ß';
            
        
        filterbuffer+=character;
        var re;
	    
	    re=new RegExp(filterbuffer,"i");
	    
        for(i=0; i<listbox.length; i++)
	    {
	        var strng=new String(listbox.options[i].text);
	        if (strng.search(re)!=-1)
	        {	
	        
	            listbox.selectedIndex = -1;               
	            listbox.options[i].selected=true;
	            if (typeof(listbox.onchange) == "function") 
	                listbox.onchange();
	            return;
	        }
	    }
	    filterbuffer=character;
	     re=new RegExp(filterbuffer,"i");
	    for(i=0; i<listbox.length; i++)
	    {
	        var strng=new String(listbox.options[i].text);
	        if (strng.search(re)!=-1)
	        {	      
	            listbox.selectedIndex = -1;                    
	            listbox.options[i].selected=true;
	            if (typeof(listbox.onchange) == "function") 
	                listbox.onchange();
	            return;
	        }
	    }
        
    }  
   
    
    
}

function toggleDisplayNone(divid) 
{
	if (document.getElementById(divid).style.display == "block") {
		document.getElementById(divid).style.display = "none";
		
	} else 
	{
		document.getElementById(divid).style.display = "block";
		
	}
}

//  *** used in  \Usersearch ***

// Moves the selected item from the source listbox to the target listbox
function moveListBoxItem(SourceListBox, TargetListBox)
{
    if(SourceListBox != null && TargetListBox != null && SourceListBox.selectedIndex >=0)
    {    
         
        var selectedValue = SourceListBox.options[SourceListBox.selectedIndex].value;
        
        var PosInTargetList = -1;
        for(i= 0; i < TargetListBox.options.length; i++)
        {
            if (TargetListBox.options[i].value == selectedValue)
            {
                PosInTargetList = i;
                break;
            }        
        }
        if(PosInTargetList >=0)
        {        
            SourceListBox.options[SourceListBox.selectedIndex] = null;
            TargetListBox.insertBefore(TargetListBox.options[PosInTargetList],TargetListBox.options[0]);
        }
        else
        {
            if(TargetListBox.options.length == 0)       
                TargetListBox.appendChild(SourceListBox.options[SourceListBox.selectedIndex]);        
            else
                TargetListBox.insertBefore(SourceListBox.options[SourceListBox.selectedIndex],TargetListBox.options[0]);
        }
       
        SourceListBox.selectedIndex = -1;
        TargetListBox.selectedIndex = -1;
        
    }
}

function addListener(element, type, expression, bubbling)  
{
    bubbling = bubbling || false;
    
    if(window.addEventListener)    
    { // Standard            
        element.addEventListener(type, expression, bubbling);            
        return true;
    } 
    else if(window.attachEvent) 
    { // IE           
        element.attachEvent('on' + type, expression);                  
        return true;
    }

    return false;
}

var SelectAllItemsListBoxIDs = new Array();
function selectAllItems(event)
{

    for(var i in SelectAllItemsListBoxIDs)
    {
        var ListBox = document.getElementById(SelectAllItemsListBoxIDs[i]);
        
        if (ListBox != null)
        {
            ListBox.style.display ='none';
            
            ListBox.multiple = true;
            for(i=0; i< ListBox.options.length; i++)
            {
                ListBox.options[i].selected = true;                
            }
            ListBox.style.display ='block';           
            
        } 
    }
}

//  ******

var netPostBack = null;
var oldOnPostBack = null;
function HijackPostBack() {    
    if(!netPostBack)
    {
        netPostBack = __doPostBack;
        __doPostBack = ExecuteCustomJSAndDoPostBack;
        if (document.forms[0].onsubmit)
            oldOnPostBack = document.forms[0].onsubmit;
        document.forms[0].onsubmit = ExecuteCustomJSAndPostBack;
    }
}

function ExecuteCustomJSAndDoPostBack(eventTarget, eventArgument) {

    ExecuteCustomJsBeforePostBack();
    return netPostBack (eventTarget, eventArgument);
}

function ExecuteCustomJSAndPostBack() {
    ExecuteCustomJsBeforePostBack();
    if (oldOnPostBack)
        oldOnPostBack();
}

function ExecuteCustomJsBeforePostBack() {
    for (var i = 0; i < kontextVar.beforePostback.length; i++) {
        eval(kontextVar.beforePostback[i]);
    }
}





function SendHashedPassword(usertbid, passwordtbid)
{
    var usertb=document.getElementById(usertbid);
    var passwordtb=document.getElementById(passwordtbid);
    var hiddenpwd=document.getElementsByName("HashedPassword")[0];
    var password=passwordtb.value; 
    passwordtb.value='';
    var request=getAsyncRequest();
 	var params='Username=' + usertb.value;
	request.open('POST',strCallbackUrl +'/Kontext/WebService/GetSalts.aspx' ,false);
	request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    request.setRequestHeader("Content-length", params.length);
    request.setRequestHeader("Connection", "close");

	request.send(params);
	if (request.responseText!='')
	{
        var salts=eval(request.responseText);
        var hashedpwd=b64_sha1(b64_sha1(password + salts.Personal)+ salts.Temporary);
        hiddenpwd.value=hashedpwd;
    }
    else
        hiddenpwd.value='failed';

}


function smartScroller_GetCoords() {
    var scrollX, scrollY;
    if (document.all) {
        if (!document.documentElement.scrollLeft)
            scrollX = document.body.scrollLeft;
        else
            scrollX = document.documentElement.scrollLeft;

        if (!document.documentElement.scrollTop)
            scrollY = document.body.scrollTop;
        else
            scrollY = document.documentElement.scrollTop;
    }
    else {
        scrollX = window.pageXOffset;
        scrollY = window.pageYOffset;
    }
    document.getElementById(hidScrollLeftId).value = scrollX;
    document.getElementById(hidScrollTopId).value = scrollY;
}


function smartScroller_Scroll() {
    var x = document.getElementById(hidScrollLeftId).value;
    var y = document.getElementById(hidScrollTopId).value;
    window.scrollTo(x, y);
}

/*** kontextOnReady ***/
function initReady(fn) {
    if (document.addEventListener) {
        document.addEventListener("DOMContentLoaded", fn, false);
    }
    else {
        document.onreadystatechange = function() { readyState(fn) }
    }
}

function readyState(fn) {
    if (document.readyState == "interactive" || document.readyState == "complete") {
        fn();
    }
}
function kontextOnReady() {
    try {

        if (typeof kontextVar != "undefined" && kontextVar && kontextVar.onReady)
            for (var i = 0; i < kontextVar.onReady.length; i++) {
            try {
                eval(kontextVar.onReady[i]);
            }
            catch (e) {
            }
        }
    }
    catch (e) {
    }
}
/*** End kontextOnReady ***/

/*** Watermark Begin ***/
function addWatermarksToTextBoxes() {
    for (var i = 0; i < kontextVar.textboxWatermarks.length; i++) {
        var tb = document.getElementById(kontextVar.textboxWatermarks[i].id);
        if (tb && tb.value == '') {
            tb.value = kontextVar.textboxWatermarks[i].w;
            tb.className += " Watermark";
        }
        tb.onfocus = onFocusWatermark;
        tb.onblur = onBlurWatermark;
    }    
}

function onFocusWatermark(ev) {
    ev = ev || window.event;
    tb = ev.srcElement || ev.target;   
    hideWatermark(tb);
}

function onBlurWatermark(ev) {
    ev = ev || window.event;
    tb = ev.srcElement || ev.target;
    showWatermark(tb);   
}



function clearWatermarks() {
    for (var i = 0; i < kontextVar.textboxWatermarks.length; i++) {
        var tb = window.document.getElementById(kontextVar.textboxWatermarks[i].id);
        hideWatermark(tb);
    }
}


function hideWatermark(textbox) {
    if (textbox && textbox.className.indexOf('Watermark') >= 0) {
        textbox.value = '';
        textbox.className = (' ' + textbox.className + ' ').replace(' Watermark ', '');
    }
}

function showWatermark(textbox) {
    if (textbox && textbox.value == '') {
        textbox.className += " Watermark";
        for (var i = 0; i < kontextVar.textboxWatermarks.length; i++) {
            if (kontextVar.textboxWatermarks[i].id == textbox.id) {
                textbox.value = kontextVar.textboxWatermarks[i].w;
                break;
            }
        }
    }
}

/*** Watermark End ***/


/*** ElementTypePropertyEditor ***/


var etpEditor = etpEditor || {};

etpEditor.postManipulation = etpEditor.postManipulation || function() {    
    var strPropIds = "";
    $('#EtPE_AssPropList li').each(function(i, elm) { strPropIds += (i > 0 ? ';' : '') + $(elm).attr('id').replace('etpePropId_', ''); });
    $('#' + kontextVar.EtPropEditor_HfId).val(strPropIds);

    $('#EtPE_ResultList li[class="disabled"]').each(function(i, elm) {
        if ($('#EtPE_ResultList #' + elm.id.replace('Dis', '')).length > 0) {
            $('#EtPE_ResultList #' + elm.id).fadeOut('slow', function() { $(this).remove() });
        }
    });
    etpEditor.setManipulationIcons();
    etpEditor.unmarkEditProp("EtPE_ResultList");
}

etpEditor.saveRelationToHf = etpEditor.saveRelationToHf || function() {
    var propID = $('#' + kontextVar.EtPropEditor_HfRelEditorId).val();
    if (propID) {
        var relations = etpEditor.deserializeRelations();
        if (!relations) {
            relations = {};
        }

        var relation = relations[propID];
        if (!relation) {
            relations[propID] = { 'dv': null, 'lab': null, 'ex': null, 'op': null };
            relation = relations[propID];
        }
        relation.dv = $('#' + kontextVar.EtPropEditor_RelDefValId).val();
        relation.lab = $('#' + kontextVar.EtPropEditor_RelLabelId).val();
        relation.ex = $('#' + kontextVar.EtPropEditor_RelExtPId).attr('checked');
        relation.op = $('#' + kontextVar.EtPropEditor_RelOptId).attr('checked');
        $('#' + kontextVar.EtPropEditor_HfRelId).val(JSON.stringify(relations));
    }

}

etpEditor.checkOverflow = etpEditor.checkOverflow || function(el) {
    var curOverflow = el.style.overflow;
    if (!curOverflow || curOverflow === "visible")
        el.style.overflow = "hidden";

    var isOverflowing = el.clientWidth < el.scrollWidth
      || el.clientHeight < el.scrollHeight;

    el.style.overflow = curOverflow;

    return isOverflowing;
}

etpEditor.ajaxFillList = etpEditor.ajaxFillList || function (listid, query, isSearchResult) {
    var url = kontextVar.ApplicationPath + '/Kontext/WebService/PropertySearch.aspx?' + query + "&time=" + new Date().getTime();
    $.getJSON(url,
                function (data) {
                    if (isSearchResult) {
                        $('#' + listid).empty();
                    }
                    $.each(data.items, function (i, item) {
                        var title = item.t;
                        var name = item.n;
                        if (name.length > 20) {
                            title += " (" + item.n + ")";
                            name = name.substr(0, 20) + "..."
                        }

                        var list = $('#' + listid);


                        if (!isSearchResult || $('#EtPE_AssPropList #etpePropId_' + item.id).length < 1) {
                            list.append('<li id="etpePropId_' + item.id + '" class="enabled"><div title="' + title + '"><img src="' + kontextVar.SysImageUrl + 'datatype_' + item.dt + '.gif"/>' + name + '</div><img/><img/><img style="cursor:pointer;" onclick="window.open(\'' + kontextVar.EtPropEditor_PropEditorUrl.replace('{0}', item.id) + '\');" src="' + kontextVar.SysImageUrl + 'OpenEtPropEditor.gif"/></li>');
                        }
                        else {
                            list.append('<li id="etpePropIdDis_' + item.id + '" class="disabled"><div title="' + title + '">' + name + '</div></li>');
                        }

                        //                        var div = jQuery("li:last div", list);
                        //                        while (div && div[0] && checkOverflow(div[0]) && name) {
                        //                            name = name.substr(0, name.length - 20)
                        //                            div.html(name + "...");
                        //                        }

                    });
                    etpEditor.setManipulationIcons();
                    $("#" + kontextVar.EtPropEditor_DivSearchBtId).removeAttr("disabled");
                });
}





etpEditor.setManipulationIcons = etpEditor.setManipulationIcons || function () {

        var resultListItems = $('#EtPE_ResultList li');
        resultListItems.each(function (index) {
            var img1 = $(this).find("img:eq(1)");            
                img1.click(etpEditor.toggleList);
                img1.attr('src', kontextVar.SysImageUrl + 'galerie_next.gif');
                $(this).find("img:eq(2)").hide();            

        });


    var assPropListItems = $('#EtPE_AssPropList li');
    assPropListItems.each(function (index) {
        var img1 = $(this).find("img:eq(1)");
        img1.click(etpEditor.toggleList);
        img1.attr('src', kontextVar.SysImageUrl + 'form_del_dis.gif');
        var img2 = $(this).find("img:eq(2)");
        img2.attr('src', kontextVar.SysImageUrl + 'i_editMod.gif');
        img2.click(etpEditor.editRelation);
        img2.show();
    });
}


etpEditor.toggleList = etpEditor.toggleList || function() {
    $(this).parent().fadeOut('fast', function() {
        var targetSelector = '#EtPE_AssPropList';
        if ($(this).parent().attr('id') == 'EtPE_AssPropList') {
            targetSelector = '#EtPE_ResultList';
            $(this).attr("class", this.className.replace(/edit/gi, ''));
            $('#' + kontextVar.EtPropEditor_DivRelEditor).fadeOut();
        }
        $(targetSelector).append(this);

        $(this).fadeIn();
       etpEditor.postManipulation()
    });
}

etpEditor.deserializeRelations = etpEditor.deserializeRelations || function() {
    try {
        return eval('(' + $('#' + kontextVar.EtPropEditor_HfRelId).val() + ')');
    }
    catch (e) {return null;}    
}

etpEditor.editRelation = etpEditor.editRelation || function() {
    etpEditor.saveRelationToHf();
    var relations = etpEditor.deserializeRelations();
    var listitem = $(this).parent();
    var propID = listitem.attr('id').replace('etpePropId_', '');
    etpEditor.unmarkEditProp("EtPE_AssPropList");
    listitem.toggleClass('edit');
    var div = jQuery("div:first", listitem);
    $('#etpeRelationLabel').attr('title', div.attr('title'));
    $('#etpeRelationLabel').html(div.html()+":");    
    if (propID) {
        $('#' + kontextVar.EtPropEditor_HfRelEditorId).val(propID);
        if (relations) {
            var relation = relations[propID];

            if (relation) {
                $('#' + kontextVar.EtPropEditor_RelDefValId).val(relation.dv);
                $('#' + kontextVar.EtPropEditor_RelLabelId).val(relation.lab);
                $('#' + kontextVar.EtPropEditor_RelExtPId).attr('checked', relation.ex);
                $('#' + kontextVar.EtPropEditor_RelOptId).attr('checked', relation.op);
                var tranlationIcon = $('#' + kontextVar.EtPropEditor_RelTransIcon);
                if (relation.lid) {
                    tranlationIcon.show();
                    tranlationIcon.unbind('click');
                    tranlationIcon.click(function() {
                        window.open(kontextVar.EtPropEditor_TranslationUrl.replace("{0}", relation.lid));
                    });
                }
                else
                    tranlationIcon.hide();
            }
        }

    }
    $('#' + kontextVar.EtPropEditor_DivRelEditor).fadeIn();
}
etpEditor.unmarkEditProp = etpEditor.addPropToAssPropList || function(ListID) {
    $('#' + ListID + ' li').each(function() { $(this).attr("class", this.className.replace(/edit/gi, '')); });
}

etpEditor.addPropToAssPropList = etpEditor.addPropToAssPropList || function(propertyId) {
    etpEditor.ajaxFillList('EtPE_AssPropList', 'pids=' + propertyId, false);
}
etpEditor.fillListFromHf = etpEditor.fillListFromHf || function() {
    etpEditor.ajaxFillList('EtPE_AssPropList', 'pids=' + $('#' + kontextVar.EtPropEditor_HfId).val() + ';&et=' + kontextVar.EtPropEditor_ElementTypeID, false);
}

etpEditor.popupWriteBackHF = etpEditor.popupWriteBackHF || function (hiddenFieldId, propID) {
    if (opener && !opener.closed) {
        var hf = opener.document.getElementById(hiddenFieldId);
        if (hf) {
            hf.value = hf.value + ';' + propID;
            opener.etpEditor.addPropToAssPropList(propID);
        }
    }
    window.close();
}

etpEditor.doSearch = etpEditor.doSearch || function() {
    var searchBt = $("#" + kontextVar.EtPropEditor_DivSearchBtId);    
    searchBt.attr("disabled", "disabled");    
    var propNameTb = document.getElementById('tbPropertySearch');
    hideWatermark(propNameTb);
    var keywords = $('#tbPropertySearch').val();
    var datatype = $('#' + kontextVar.EtPropEditor_DtDllId).val();
    var category = $('#' + kontextVar.EtPropEditor_CatDllId).val();
    etpEditor.ajaxFillList('EtPE_ResultList', 'kw=' + keywords + '&dt=' + datatype + '&cat=' + category, true);
    showWatermark(propNameTb);

}


var JSON = JSON || {};

// implement JSON.stringify serialization
JSON.stringify = JSON.stringify || function(obj) {

    var t = typeof (obj);
    if (t != "object" || obj === null) {

        // simple data type
        if (t == "string") obj = '"' + obj + '"';
        return String(obj);
    }
    else {

        // recurse array or object
        var n, v, json = [], arr = (obj && obj.constructor == Array);

        for (n in obj) {
            v = obj[n]; t = typeof (v);

            if (t == "string") v = '"' + v.replace('"','\\\"') + '"';
            else if (t == "object" && v !== null) v = JSON.stringify(v);

            json.push((arr ? "" : '"' + n + '":') + String(v));
        }

        return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
    }
};

/*** End ElementTypePropertyEditor ***/


/* Session Expiration Warning  */
function AutExpWarningSetPosition() {

    var div = document.getElementById("AutExpWarning");
    var x = document.body.scrollLeft + 10;
    var y = document.body.scrollTop + document.body.clientHeight - 70;
    div.style.left = x;
    div.style.top = y;
}

var AutExpRemainingSeconds;
function AutExpWarningCountdown(renewAuthentication) {
    if (renewAuthentication) {


        var request = getAsyncRequest();
        request.open('POST', kontextVar.ApplicationPath + '/Kontext/WebService/PropertySearch.aspx');
        request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        request.setRequestHeader("Connection", "close");
        request.send();
        document.getElementById("AutExpWarning").attributes['class'].value = "ExpWarningHidden";
        AutExpRemainingSeconds = null;

    }
    else {
        if (!AutExpRemainingSeconds)
            AutExpRemainingSeconds = kontextVar.autExpWarning_Duration;
        if (AutExpRemainingSeconds > 0) {
            AutExpRemainingSeconds--

            var lastLevel = kontextVar.autExpWarning_Levels.length - 1;
            if (AutExpRemainingSeconds <= kontextVar.autExpWarning_Levels[lastLevel]) {
                var level = lastLevel;
                for (var i = lastLevel; i >= 0; i--) {
                    if (kontextVar.autExpWarning_Levels[i] >= AutExpRemainingSeconds) {
                        level = i;
                    }
                }
                var div = document.getElementById("AutExpWarning");
                if (div.parentNode.tagName != "BODY") {
                    document.body.appendChild(div);
                    window.onscroll = AutExpWarningSetPosition;
                    window.onresize = AutExpWarningSetPosition;
                    AutExpWarningSetPosition();
                }
                div.attributes['class'].value = kontextVar.autExpWarning_Classes[level];
                var remainingSecsText = new String(AutExpRemainingSeconds % 60);
                if (remainingSecsText.length == 1)
                    remainingSecsText = '0' + remainingSecsText;
                div.getElementsByTagName("div")[0].innerHTML = kontextVar.autExpWarning_WarningText.replace("\{0\}", Math.floor(AutExpRemainingSeconds / 60) + ':' + remainingSecsText);
            }
        }
        if (AutExpRemainingSeconds <= 0) {
            document.getElementById("AutExpWarning").attributes['class'].value = "ExpWarningHidden";
            if (kontextVar.autExpWarning_AlertText) {
                window.alert(kontextVar.autExpWarning_AlertText)
                window.open(kontextVar.ApplicationPath + '/Kontext/Editing/Dialogs/LogonDialog.aspx?logoff=true&closewindow=true&allowreconnect=true', 'logon', 'height=500,width=500,resizable=yes,scrollbars=yes,status=no,location=no,toolbar=no,menubar=no', true);
            }
        }
        else {
            window.setTimeout('AutExpWarningCountdown()', 1000)
        }  
        }
    }

/* End Session Expiration Warning  */

    /* CategoryTags */

    var CategoryTags = CategoryTags || {};

    CategoryTags.Init = CategoryTags.Init || function() {    
        $('div.CategoriesContainer').bind('contextmenu', function () { return CategoryTags.showContextMenu(this); });
        $('div.CategoriesContainer div[placeholder=true]').live('click', function () { return CategoryTags.showContextMenu($(this).parent()); });
        $('div.CategoriesContainer div[placeholder!=true]').live('click', function () { return CategoryTags.existingCatClick(this); });
        $('div.CategoriesEditor li').click(function () { return CategoryTags.editorClick(this); });
    }

    CategoryTags.showContextMenu = CategoryTags.showContextMenu || function(container) {    
        var editor = $("div.CategoriesEditor:first");
        $(container).next().append(editor);
        editor.find("li[catid] > div").removeClass("selected");

        $(container).find("div[catid]").each(function (index) {
            var catid = $(this).attr("catid");
            if (catid) {
                editor.find("li[catid=" + catid + "] > div:first").addClass("selected");
            }
        });

        editor.fadeIn('normal');
        $(document.body).one('click', function () {
            CategoryTags.hideContextMenu();
        });
        return false;
    }

        CategoryTags.hideContextMenu = CategoryTags.hideContextMenu || function() {    
        $("div.CategoriesEditor:first").fadeOut('fast');
    }


    CategoryTags.existingCatClick = CategoryTags.existingCatClick || function(container) {    
        var cat = $(container)
        var catid = cat.attr('catid');
        var elementid = cat.parent().attr("appelid");
        CategoryTags.setCategory (elementid, catid, false)
    }


    
    CategoryTags.editorClick = CategoryTags.editorClick || function(listitem) {    
        var li = $(listitem);
        var editor = li.parents("div:first")
        editor.fadeOut();
        var elementid = editor.parent().prev().attr("appelid");
        var catid = li.attr("catid");
        var add = !li.find("div:first").hasClass("selected");
        CategoryTags.setCategory(elementid, catid, add)
    }

    CategoryTags.setCategory = CategoryTags.setCategory || function (elementid, catid, add) {
        var url = kontextVar.ApplicationPath + '/Kontext/WebService/SetTagCategory.aspx?elid=' + elementid + '&catid=' + catid + '&add=' + add + '&time=' + new Date().getTime();
        
        var test = $.getJSON(url, function (data) {
            if (data && data.success) {
                if (data.action == "add") {
                    try {
                        var catDef = eval('kontextVar.TagCategoriesList.cat_' + data.categoryid);
                        var catHtml = kontextVar.TagCategoriesFormatString.replace('{0}', catDef.c).replace('{1}', catDef.t).replace('{2}', data.categoryid);
                        $('div.CategoriesContainer[appelid=' + data.elementid + ']:first > div[catid=' + data.categoryid + ']').fadeOut();
                        $('div.CategoriesContainer[appelid=' + data.elementid + ']:first > div[placeholder]').remove();
                        $('div.CategoriesContainer[appelid=' + data.elementid + ']:first').append(catHtml);


                        // $('div.CategoriesContainer[appelid=' + data.elementid + ']:first').remove('div[placeholder]');
                        //$('div.CategoriesContainer[appelid=' + data.elementid + ']:first').remove('div[catid=' + data.categoryid + ']');
                    }
                    catch (e) {
                        alert(e);
                    }
                }
                else { //remove
                    $('div.CategoriesContainer[appelid=' + data.elementid + ']:first > div[catid=' + data.categoryid + ']').fadeOut('normal', function () {
                        $('div.CategoriesContainer[appelid=' + data.elementid + ']:first > div[catid=' + data.categoryid + ']').remove();
                        if ($('div.CategoriesContainer[appelid=' + data.elementid + ']:first > div').length <= 0) {
                            $('div.CategoriesContainer[appelid=' + data.elementid + ']:first').append(kontextVar.TagCategoriesPlaceholder);
                        }
                    });
                }
            }
            else {
                //alert('fehler!');
            }
        });
    }




    /* End CategoryTags */





    