var LastID = "";

AutoCompletionInfo = new function()
{
	var LastActionControl = "";
	var LastXPos = 0;
	var LastYPos = 0;
	var ActionList = "";
}

function ResetAutoCompletionInfo()
{
	AutoCompletionInfo.LastActionControl = "";
	AutoCompletionInfo.LastXPos = 0;
	AutoCompletionInfo.LastYPos = 0;
	AutoCompletionInfo.ActionList = "";
}

function insertAtCursor(myField, myValue)
{


var myField = document.getElementById(myField);

//CurrentInformation.TextBoxPosition

// insert at previous cursor position
part1 = myField.value.substr(0, CurrentInformation.TextBoxPosition+1);
part2 = myField.value.substr(CurrentInformation.TextBoxPosition+1);
myField.value = part1+myValue+part2;

/*
myField.focus();
	if (document.selection)
	{
		myField.focus();
		sel = document.selection.createRange();

		sel.text = myValue;
		myField.focus();
	}
//
//MOZILLA/NETSCAPE support
	else if (myField.selectionStart || myField.selectionStart == '0')
	{
		var startPos = myField.selectionStart;
		var endPos = myField.selectionEnd;
		var cursorPos = startPos + myValue.length;

		//
		myField.value = myField.value.substring(0, startPos)
		+ myValue
		+ myField.value.substring(endPos, myField.value.length);
		//
		myField.selectionStart = cursorPos;
		myField.selectionEnd = cursorPos;
	}
	else
	{
		myField.value += myValue;
	}*/
myField = null;
}
function findPos(obj) {
	var curleft = 0;
	var curtop = 0;
	if (obj.offsetParent) {
		do
		{
			// break if the parent control data box is reached
			if (obj.id == "cwAutoControl[Databox]")
			{
				break;
			}
			else
			{
				curleft += obj.offsetLeft;
				curtop += obj.offsetTop;
			}
		} while (obj = obj.offsetParent);
	}
	return [curleft,curtop];
}
/*
function getPosition(element)
 //der Aufruf dieser Funktion ermittelt die absoluten Koordinaten
 //  des Objekts element
{
  var elem=element,tagname="",x=0,y=0;

 //solange elem ein Objekt ist und die Eigenschaft offsetTop enthaelt
  // wird diese Schleife fuer das Element und all seine Offset-Eltern ausgefuehrt
  while ((typeof(elem)=="object")&&(typeof(elem.tagName)!="undefined"))
  {
    y+=elem.offsetTop;      //Offset des jeweiligen Elements addieren
    x+=elem.offsetLeft;   // Offset des jeweiligen Elements addieren
    tagname=elem.tagName.toUpperCase();  //tag-Name ermitteln, Grossbuchstaben

 //wenn beim Body-tag angekommen elem fuer Abbruch auf 0 setzen
    if (tagname=="BODY")
      elem=0;

//wenn elem ein Objekt ist und offsetParent enthaelt
   //Offset-Elternelement ermitteln
    if (typeof(elem)=="object")
      if (typeof(elem.offsetParent)=="object")
        elem=elem.offsetParent;
  }

// Objekt mit x und y zurueckgeben
  position=new Object();
  position.x=x;
  position.y=y;
  return position;
}*/

function GetCursorPosition(object)
{
	// unshow the possibly selected control
	if(LastID != null)
		UnshowControl(LastID, true);
	LastID = null;
	
	HideAutoCompletionBox();
	var CharacterHeight = 16;
	var CharacterWidth = 8.2;

	// load value into variable
	CurrentContext = object.value;

	// IE get current position
	if( document.selection ){
		// The current selection
		var range = document.selection.createRange();
		// We'll use this as a 'dummy'
		var stored_range = range.duplicate();
		// Select all text
		stored_range.moveToElementText( object );
		// Now move 'dummy' end point to end point of original range
		stored_range.setEndPoint( 'EndToEnd', range );
		// Now we can calculate start and end points
		object.selectionStart = stored_range.text.length - range.text.length;
		object.selectionEnd = object.selectionStart + range.text.length;
		
		range = null;
		stored_range = null;
	}

	// get current position FF only - IE fix above
	var currentPosition = object.selectionStart-1;


	//alert(currentPosition);
	CurrentContext = CurrentContext.substr(0, currentPosition+1);

	var currentXPosition = currentPosition - CurrentContext.lastIndexOf("\n");
	var currentXPosition = (currentXPosition > object.cols) ? 0 : currentXPosition;
	var lines = CurrentContext.split("\n").length;

	lines = (lines > object.rows) ? object.rows+1 : lines;

	// get the element position
	//elementPosition = getPosition(object);
	var elementPosition = findPos(object);
	//elementData = findPos(document.getElementById("cwAutoControl[Databox]"));



	CurrentInformation.TextBoxPosition = currentPosition;

	//alert("X: "+elementData[0]+" Y:"+elementData[1]);

	var TotalX = elementPosition[0] + (currentXPosition * CharacterWidth);
	var TotalY = elementPosition[1] + (lines * CharacterHeight);


	//alert(object.style.fontSize);

	//document.getElementById("results").value = TotalX + " / " + TotalY;

	GetVariableString(CurrentContext, currentPosition, TotalX, TotalY);
	//GetVariableString(CurrentContext, currentPosition, document.getElementById("cwAutoControl[Databox]").style.left, document.getElementById("cwAutoControl[Databox]").style.top);

//	box = document.getElementById('AutoCompletion');
//	box.style.position = "absolute";
//	box.style.display = "block";
//	box.style.left = CurrentInformation.DataboxDimensions[0];
//	box.style.top = CurrentInformation.DataboxDimensions[1];
//
}

function GetVariableString(context, cursorPosition, X, Y)
{
	var cursorcontext = context.substr(0, cursorPosition+1);

	var openingcharacter = "{";
	var closingcharacter = "}";
	// get the last position of a possible opening {
	var lastOpeningPosCC = cursorcontext.lastIndexOf(openingcharacter);
	var lastClosingPosCC = cursorcontext.lastIndexOf(closingcharacter);

	var nextOpeningPos = context.indexOf(openingcharacter);
	var nextClosingPos = context.indexOf(closingcharacter);

	var unhide = false;
	// now check if the cursor is right after a curly brace
	if (lastOpeningPosCC != -1)
	{
	    // get the type if available

	    if (lastOpeningPosCC == cursorPosition)
	    {
	        ShowAutoCompletionBox(X,Y, "choose");
	        unhide = true;
	    }
	    var FieldSyntax = new Array ("{field:", "{var:", "{sysvar:", "{appvar:", "{action:", "{text:", "{repeater:", "{id:");

	    for (var a = 0; a < FieldSyntax.length; a++)
	    {
	        //alert(cursorcontext.substr(cursorPosition-FieldSyntax.length+1));
	         //if (cursorcontext.substr(cursorPosition-FieldSyntax[i].length+1).toLowerCase() == FieldSyntax[i].toLowerCase())

	        if (GetCurrentSection() == FieldSyntax[a].toLowerCase())
	        {
	            ShowAutoCompletionBox(X,Y, FieldSyntax[a].toLowerCase());
	            unhide = true;
	        }
	    }
	}

	/*if (!unhide)
	{
	    // Hide box
	    HideAutoCompletionBox();
	} */

}
function ClearFunctionName(functionName)
{
    return functionName.replace(/[{:]/g, "");
}
function ShowAutoCompletionBox(X,Y, BoxType)
{
	AutoCompletionInfo.LastXPos = X;
	AutoCompletionInfo.LastYPos = Y;

	var box = null;
	if(ClearFunctionName(BoxType).toLowerCase() == "action" && AutoCompletionInfo.LastActionControl == "")
	{
		AutoCompletionInfo.LastActionControl = 'AutoCompletion_SelectAction';
		box = document.getElementById('AutoCompletion_SelectAction');
		box.style.position = "absolute";
		box.style.display = "block";
		//box.style.background = "grey";
		box.style.left = X + 'px';
		box.style.top = Y + 'px';
		box.style.zIndex = 10;
		box = null;
		return;
	}
	box = null;
	AutoCompletionInfo.LastActionControl = 'AutoCompletion_'+ClearFunctionName(BoxType).toLowerCase();
	box = document.getElementById('AutoCompletion_'+ClearFunctionName(BoxType).toLowerCase());
	box.style.position = "absolute";
	box.style.display = "block";
	//box.style.background = "grey";
	box.style.left = X + 'px';
	box.style.top = Y + 'px';
	box.style.zIndex = 10;
	term = GetCurrentArgument(true);

	//if (document.getElementById(term) != null)
	//{
		//alert(term);
		LastID = term;
		//console.info(term);
		ShowControl(term, true);
	//}

	//box.innerHTML = ClearFunctionName(BoxType);
	if (ClearFunctionName(BoxType) == "var" && InfoCache.Variables.length > 0)
	{
	    box.innerHTML = "";
	    term = GetCurrentArgument();


	    var maxcount = 100;
	    var matches = 0;
	    // now fill the auto completion box
	    for (var i = 0; i < InfoCache.Variables.length; i++)
	    {
	    	// limit the suggestions
	        if (i < maxcount)
	        {
		        if (InfoCache.Variables[i][0].substr(0, term.length).toLowerCase() == term.toLowerCase() || InfoCache.Variables[i][1].substr(0, term.length).toLowerCase() == term.toLowerCase())
		        {
		            box.innerHTML += "<a href=\"javascript:SetArgument('"+InfoCache.Variables[i][0]+"')\">"+HighlightString(term, InfoCache.Variables[i][0])+" <i>("+HighlightString(term, InfoCache.Variables[i][1])+")</i></a> <br>";
		        	matches++;
		        }
	        }
	    }

	    if (matches == 0)
	    {
	    	HideAutoCompletionBox();
	    }
	}
	else if(ClearFunctionName(BoxType) == "sysvar" && InfoCache.SysVariables.length > 0)
	{
	    box.innerHTML = "";
	    term = GetCurrentArgument();


	    var maxcount = 100;
	    var matches = 0;
	    // now fill the auto completion box
	    for (var i = 0; i < InfoCache.SysVariables.length; i++)
	    {
	    	// limit the suggestions
	        if (i < maxcount)
	        {
		        if (InfoCache.SysVariables[i][0].substr(0, term.length).toLowerCase() == term.toLowerCase() || InfoCache.SysVariables[i][1].substr(0, term.length).toLowerCase() == term.toLowerCase())
		        {
		            box.innerHTML += "<a href=\"javascript:SetArgument('"+InfoCache.SysVariables[i][0]+"')\">"+HighlightString(term, InfoCache.SysVariables[i][0])+" <i>("+HighlightString(term, InfoCache.SysVariables[i][1])+")</i></a> <br>";
		        	matches++;
		        }
	        }
	    }

	    if (matches == 0)
	    {
	    	HideAutoCompletionBox();
	    }		
	}
	else if(ClearFunctionName(BoxType) == "appvar" && InfoCache.AppVariables.length > 0)
	{
	    box.innerHTML = "";
	    term = GetCurrentArgument();


	    var maxcount = 100;
	    var matches = 0;
	    // now fill the auto completion box  
	    for (var i = 0; i < InfoCache.AppVariables.length; i++)
	    {
	    	// limit the suggestions
	        if (i < maxcount)
	        {
		        if (InfoCache.AppVariables[i][0].substr(0, term.length).toLowerCase() == term.toLowerCase() || InfoCache.AppVariables[i][1].substr(0, term.length).toLowerCase() == term.toLowerCase())
		        {
		            box.innerHTML += "<a href=\"javascript:SetArgument('"+InfoCache.AppVariables[i][0]+"')\">"+HighlightString(term, InfoCache.AppVariables[i][0])+" <i>("+HighlightString(term, InfoCache.AppVariables[i][1])+")</i></a> <br>";
		        	matches++;
		        }
	        }
	    }

	    if (matches == 0)
	    {
	    	HideAutoCompletionBox();
	    }		
	}
	else if(ClearFunctionName(BoxType) == "action")
	{
		box.innerHTML = AutoCompletionInfo.ActionList;
		ResetAutoCompletionInfo();

	}
	else if(ClearFunctionName(BoxType) == "text")
	{
		box.innerHTML = "";
		if(term != "")
		{
			box.innerHTML = "<span style=\"border-bottom:1px solid #000;\"><b><a href=\"javascript:ShowTranslationTemplate('"+term+"')\">"+ServerVars.Language.EditTranslation+"</a><b></span><br>";
		}
		box.innerHTML = box.innerHTML + "<span id=\"cwAutoControl[AvailableTranslations]\"></span>";
		/*cwOffice.jS.queue.pA.clear();
		try{
			cwOffice.jS.xhr.obj.abort();
		}catch(e){

		}*/
		jS.queue.pA.set({"php":[
								"BerkeWebflowEditorLogicDatabox","GetAvailableTranslations"
							],
							"event":"click",
							"getControls":[
								{"Name":"TextKey","attributes" :{"value":term}},
								{"Name":"GlobalCwAppID","getAttributes":{"value":true}},
		    					{"Name":"GlobalCwAppVersion","getAttributes":{"value":true}}
							]});
	}
	var box = null;
}
function ShowTranslationTemplate(Key)
{
	var box = document.getElementById('cwAutoControl[AutoCompletion_text_edit]');
	box.style.display = "block";
	box.style.position = "absolute";
	box.style.display = "block";
	box.style.left = AutoCompletionInfo.LastXPos + 'px';
	box.style.top = AutoCompletionInfo.LastYPos + 'px';
	box.style.zIndex = 10;

	jS.queue.pA.set({"php":[
							"BerkeWebflowEditorLogicDatabox","ShowTranslationTemplate"
						],
						"event":"click",
						"getControls":[
							{"Name":"TextKey","attributes" :{"value":Key}},
							{"Name":"GlobalCwAppID","getAttributes":{"value":true}},
		    				{"Name":"GlobalCwAppVersion","getAttributes":{"value":true}}
						]});

	box = null;
	box = document.getElementById('AutoCompletion_text');
	box.style.display = "none";
	
	box = null;
}
function HideAutoCompletionBox()
{
	var box = document.getElementById('AutoCompletion_choose');
	box.style.display = "none";
	box = null;
	box = document.getElementById('AutoCompletion_field');
	box.style.display = "none";
	box = null;
	box = document.getElementById('AutoCompletion_repeater');
	box.style.display = "none";
	box = null;
	box = document.getElementById('AutoCompletion_id');
	box.style.display = "none";
	box = null;
	box = document.getElementById('AutoCompletion_var');
	box.style.display = "none";
	box = null;
	box = document.getElementById('AutoCompletion_sysvar');
	box.style.display = "none";
	box = null;
	box = document.getElementById('AutoCompletion_appvar');
	box.style.display = "none";
	box = null;
	box = document.getElementById('AutoCompletion_action');
	box.style.display = "none";
	box = null;
	box = document.getElementById('AutoCompletion_SelectAction');
	box.style.display = "none";
	box = null;
	box = document.getElementById('AutoCompletion_text');
	box.style.display = "none";
	box = null;
	box = document.getElementById('cwAutoControl[AutoCompletion_text_edit]');
	box.style.display = "none";
	box.innerHTML = "";
	box = null;
}
function HideAutoCompletionBoxTextEdit()
{
	var box = document.getElementById('cwAutoControl[AutoCompletion_text_edit]');
	box.style.display = "none";
	box = null;
}
function InsertMessage(Message, Mode)
{
	var object = document.getElementById('cwAutoControl[SQLStatement]');
	if(!object)
	{
		object = document.getElementById('cwAutoControl[RequiredFieldMessage]');
	}
	if(!object)
	{
		object = document.getElementById('cwAutoControl[ConfirmationMessage]');
	}

	var context = object.value;

	// get current position FF only
	var cursorPosition = CurrentInformation.TextBoxPosition;

	var cursorcontext = context.substr(0, cursorPosition+1);

	var openingcharacter = "{";
	var closingcharacter = "}";

	// get the last position of a possible opening {
	var lastOpeningPosCC = cursorcontext.lastIndexOf(openingcharacter);
	var lastClosingPosCC = cursorcontext.lastIndexOf(closingcharacter);

	var nextOpeningPos = context.substr(cursorPosition+1).indexOf(openingcharacter);
	var nextClosingPos = context.substr(cursorPosition+1).indexOf(closingcharacter);

	var attachclosing = false;
	//alert(context.substr(cursorPosition+1)+" OPEN: "+nextOpeningPos+" CLOSE:" + nextClosingPos);
	// check if the closing char needs to be placed
	if ( (nextClosingPos > nextOpeningPos) || nextClosingPos < 0)
	{
		attachclosing = true;
	}

	// make sure that this exeption works as well
	var attachclosing = (nextOpeningPos < 0 && nextClosingPos == 0) ? false : attachclosing;
	// field
	if (Mode == 1)
	{
		Message = (attachclosing) ? Message+"}" : Message;

		// now check if "field:" needs to be pasted as well
		//alert(cursorcontext.substr(cursorPosition-5).toLowerCase());
		if (cursorcontext.substr(cursorPosition-5).toLowerCase() != "field:")
		{
			Message = "field:"+Message;
		}

		insertAtCursor(object.id, Message);

		// hide the autocompletion box
		HideAutoCompletionBox();
	}
	// variable
	if (Mode == 2)
	{
		Message = (attachclosing) ? Message+"}" : Message;

		// now check if "field:" needs to be pasted as well
		//alert(cursorcontext.substr(cursorPosition-5).toLowerCase());
		if (cursorcontext.substr(cursorPosition-5).toLowerCase() != "field:")
		{
			Message = "var:"+Message;
		}

		insertAtCursor(object.id, Message);

		// hide the autocompletion box
		HideAutoCompletionBox();
	}
	if(Mode == 3)
	{
		//Message = (attachclosing) ? Message+"}" : Message;
		Message = "action:"+Message;
		insertAtCursor(object.id, Message);

		// hide the autocompletion box
		//HideAutoCompletionBox();
	}
	if(Mode == 4)
	{
		Message = "text:"+Message;
		insertAtCursor(object.id, Message);

		HideAutoCompletionBox();
	}
	if(Mode == 5)
	{
		Message = "repeater:"+Message;
		insertAtCursor(object.id, Message);

		HideAutoCompletionBox();
	}
	if(Mode == 6)
	{
		Message = "id:"+Message;
		insertAtCursor(object.id, Message);

		HideAutoCompletionBox();
	}
	if(Mode == 7)
	{
		Message = (attachclosing) ? Message+"}" : Message;
		
		Message = "sysvar:"+Message;
		insertAtCursor(object.id, Message);

		HideAutoCompletionBox();
	}
	if(Mode == 8)
	{
		Message = (attachclosing) ? Message+"}" : Message;
		Message = "appvar:"+Message;
		insertAtCursor(object.id, Message);

		HideAutoCompletionBox();
	}
	object = null;
}

InfoCache = new function()
{
    this.Variables = new Array();
    this.AppVariables = new Array();
    this.SysVariables = new Array();
}

function AddVariable(Varname, Description, type)
{
	switch(type)
	{
		case 'sys':
			InfoCache.SysVariables.push(new Array(Varname, Description)); 
		break;
		case 'app':
			InfoCache.AppVariables.push(new Array(Varname, Description));
		break;
		case 'var':
		default:
    		InfoCache.Variables.push(new Array(Varname, Description));
    }
    
}
function ClearVariables(type)
{
	switch(type)
	{
		case 'sys':
			InfoCache.SysVariables = new Array(); 
		break;
		case 'app':
			InfoCache.AppVariables = new Array();
		break;
		case 'var':
		default:
    		InfoCache.Variables = new Array();
    }
}
/* Testvars
AddVariable("balls", "Cupboard 14");
AddVariable("brooms", "Cupboard 12");
AddVariable("beer", "Cupboard 1");
AddVariable("wine", "Cupboard 2");
AddVariable("winter salmon", "Cupboard 24");
AddVariable("winex", "Cupboard Software");*/


function GetCurrentArgument(GetCompleteArgument)
{

   var object = document.getElementById("cwAutoControl[SQLStatement]");
    if(!object)
    {
    	object = document.getElementById('cwAutoControl[RequiredFieldMessage]');
    }
    if(!object)
	{
		object = document.getElementById('cwAutoControl[ConfirmationMessage]');
	}
    //pos = object.selectionStart-1+1;


    var pos = 0;
    if (!GetCompleteArgument)
    {
    	pos = CurrentInformation.TextBoxPosition+1;
    }
    else
    {
    	pos = CurrentInformation.TextBoxPosition+1;
    	pos = pos + object.value.substr(pos,object.value.substr(pos).indexOf("}")).length;

    }
     var context = object.value.substr(0, pos);
     object = null;
    return context.substr(context.lastIndexOf(":")+1);
}
function GetCurrentSection()
{
    var object = document.getElementById("cwAutoControl[SQLStatement]");
    if(!object)
    {
    	object = document.getElementById('cwAutoControl[RequiredFieldMessage]');
    }
    if(!object)
	{
		object = document.getElementById('cwAutoControl[ConfirmationMessage]');
	}
    //pos = object.selectionStart-1+1;
    var pos = CurrentInformation.TextBoxPosition+1;

    var context = object.value.substr(0, pos).toLowerCase();
    var vRet = "";

    if (context.lastIndexOf("}") < context.lastIndexOf("{"))
    {
         vRet = context.substr(context.lastIndexOf("{"), context.lastIndexOf(":")-context.lastIndexOf("{")+1);
    }
    object = null;
    return vRet;
}
function HighlightString(Part, WholeString)
{
    var part2 = WholeString.substr(Part.length)



    var highlightedstring = WholeString;
    // make sure the term is correct
    if (WholeString.substr(0, Part.length).toLowerCase() == Part.toLowerCase())
    {
        highlightedstring = WholeString.substr(0, Part.length).bold()+part2;
    }
    return highlightedstring;
}
function SetArgument(Argument)
{
    var object = document.getElementById("cwAutoControl[SQLStatement]");
    if(!object)
    {
    	object = document.getElementById('cwAutoControl[RequiredFieldMessage]');
    }
    if(!object)
	{
		object = document.getElementById('cwAutoControl[ConfirmationMessage]');
	}
    //pos = object.selectionStart-1+1;
    var pos = CurrentInformation.TextBoxPosition+1;

    var context = object.value.substr(0, pos);

    var part1 = context.substr(0, context.lastIndexOf(":")+1);
    var part2 = 0;

    if (object.value.substr(pos).indexOf("}") != -1 && object.value.substr(pos).indexOf("}") < object.value.substr(pos).indexOf("{"))
    {
        part2 = object.value.substr(pos).substr(object.value.substr(pos).indexOf("}"));
    }
    else
    {
    	if (object.value.substr(pos).indexOf("}") < object.value.substr(pos).indexOf("{") || (object.value.substr(pos).indexOf("}") != -1 && object.value.substr(pos).indexOf("{") == -1))
    	{
        	part2 = object.value.substr(pos).substr(object.value.substr(pos).indexOf("}"));
    	}
    	else
    	{
    		part2 = "}"+object.value.substr(pos);
    	}
    }
    object.value = part1+Argument+part2;
    HideAutoCompletionBox();

    object = null;
}
function FCK_KeyUp(editorInstance)
{
	//GetCursorPosition(editorInstance.EditorDocument);
}
//function FCK_Save()
//{
//	alert('speichern...!');
//
//	return false;
//}
//function FCKeditor_OnComplete( editorInstance ) {
//    if (document.all) {
//    // IE
//        editorInstance.EditorDocument.attachEvent("onkeyup", function() {FCK_KeyUp(editorInstance)}) ;
//    } else {
//       // other browser
//       editorInstance.EditorDocument.addEventListener( 'keyup', function() {FCK_KeyUp(editorInstance)}, true ) ;
//    }
//
//    editorInstance.LinkedField.form.onsubmit = FCK_Save;
//}
