
// the array which holds the options in the format key##value
optionsArray=new Array();

function draw_cont(cont, id, x, y) {
	var div = document.createElement("div");
	if (id!="") div.id=id;
	div.style.position="absolute";
	div.style.zIndex=1000;
	div.style.left=x+"px";
	div.style.top=y+"px";
	return cont.appendChild(div);
}

function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1) 
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }

  function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }
  
function _getKey(e)
{
    if (document.all)
        return window.event.keyCode;
    else
        return e.keycode ? e.keycode : e.which;
}

function _cancelKeyEvent(e)
{
    if (document.all)
        window.event.keyCode=null;
    else
        e.cancelBubble=true;
}

function _removeNode(node) {
	if (document.all) {
		node.removeNode(true);
		return;
	}
	for(var i = (node.childNodes.length - 1); i >= 0; i--)
		_removeNode(node.childNodes[i]);
	node.parentNode.removeChild(node);
}

// displays an autocomplete popup box bound to a given textbox
// keyboxId specifies the id of a (possibly hidden) key field that will receive the key of the selected value
// textboxId specifies the id of the textbox on which to bound the suggestion dropdown
// optional withKey (true/ false - default TRUE): whether the elements of the options array are simple values or contain a couple key,value separated by ##
// optional mode: if mode=="forcePrefix" the typed values must begin with one of the given options
// optional suggestWhenEmpty: if TRUE, the suggestion starts also with empty textbox
// PUBLIC METHODS
// setOptions(Array options): sets the array of options for the suggestion box 
function suggestionDiv(keyboxId, textboxId, withKey, mode, suggestWhenEmpty)
{
	this.suggestDiv=null;
	this.suggestIndex=-1;
	this.maxIndex=-1;
	var maxHeight=150;
	var lineHeight=30;
	var optionsArray=new Array();
	
	var keyboxControl=null;
	if (keyboxId!="")
		keyboxControl=getControl(keyboxId);
		
    if (withKey==null || withKey==undefined)
        withKey=true;
    if (mode==null || mode==undefined)
        mode="";
	
	var self=this;

    this.setOptions=function(options)
    {
        if (options==undefined || options==null)
            optionsArray=new Array();
        else
            optionsArray=options;
        var locality = getControl(textboxId);
        // locality.value ='';
        this.takeValue();
    }

	this.divOpen=function()
	{
		var tbox=getControl(textboxId);
	    this.suggestDiv=draw_cont(document.body, "sugg", findPosX(tbox), findPosY(tbox)+20);
	    this.suggestDiv.style.height=maxHeight+"px";
	    this.suggestDiv.style.width=parseInt(tbox.offsetWidth)+"px";
	    this.suggestDiv.style.overflowY="auto";
		this.suggestDiv.style.backgroundColor="#ffffff";
		this.suggestDiv.style.borderWidth="1px";
		this.suggestDiv.style.borderStyle="solid";
		this.suggestDiv.style.borderTopStyle="none";
		this.suggestDiv.style.fontSize="10px";
		
		var iframe = document.createElement('iframe');
		with (iframe.style)
	    {
		    position = 'absolute';
		    display="block";
		    height = this.suggestDiv.style.height;
		    width = this.suggestDiv.style.width;
		    left = this.suggestDiv.style.left;
		    top = this.suggestDiv.style.top;
		    border = '0';
	    }
	    iframe.src="../Shared/img/logo.gif";
	    this.iframe=document.body.appendChild(iframe);
	    this.iframe.style.zIndex=2;
	}
	
	this.divClose=function()
	{
	    if (self.suggestDiv!=null)
	    {
		    _removeNode(self.suggestDiv);
		    self.suggestDiv=null;
		    _removeNode(self.iframe);
		}
		self.suggestIndex=-1;
		self.maxIndex=-1;
		
		// before leaving, we check whether the final string
		// matches one of the suggestion strings. In that case,
		// we copy the corresponding key into the hidden field (if given)
		var text=getControl(textboxId).value.toUpperCase();
		if (keyboxControl!=null)
		    getControl(keyboxId).value="";
    
        //if (text!="") getControl("sdfsfdf").value="";
		var optionText;
		for (var k=0; k<optionsArray.length; k++)
		{
		    if (withKey) optionText=optionsArray[k].split("##")[1].toUpperCase();
		    else optionText=optionsArray[k].toUpperCase();
		
		    if (text==optionText)
		    {
		        if (keyboxControl!=null && withKey)
		            getControl(keyboxId).value=optionsArray[k].split("##")[0];
		        getControl(textboxId).value=optionText;
		    }
		}
		// alert(getControl(keyboxId).value);
	}
	
	this.takeValue=function()
	{
	    this.divClose();
	}
	
	this.suggestPop=function(e)
	{
		var keyCode=_getKey(e);
		if (keyCode==40)
		{
			self.scrollDown();
			return;
		}
		if (keyCode==38)
		{
			self.scrollUp();
			return;
		}
		if (keyCode==13)
		{
			self.select();
			self.divClose();
			return false;
		}
        if (keyCode==9)
		{
		    self.select();
			self.divClose();
			return;
		}
		if (keyCode==16)
		    return;
		
		if (mode=="forcePrefix" && keyCode!=8)
		{
		    if (!self.checkPrefix(keyCode))
		        return false;
		}
		
		globalPointer=self;
		setTimeout("globalPointer.suggestPop2();", 200);
	}
	
	this.scrollDown=function()
	{
		if (this.suggestIndex>=this.maxIndex)
			return;
		if (this.suggestIndex>-1)
		{
			document.getElementById("srow"+this.suggestIndex).style.backgroundColor="#ffffff";
		}
		this.suggestIndex+=1;
		
		var newRow=document.getElementById("srow"+this.suggestIndex);
		
	    newRow.style.backgroundColor="yellow";
	    
	    if (this.suggestDiv.scrollTop+maxHeight<newRow.offsetTop+lineHeight)
	    {
	        this.suggestDiv.scrollTop+=lineHeight;
	    }
	        
	}
	
	this.scrollUp=function()
	{
		if (this.suggestIndex<=0)
			return;
		if (this.suggestIndex>-1)
		{
			document.getElementById("srow"+this.suggestIndex).style.backgroundColor="#ffffff";
		}
		this.suggestIndex-=1;
		
	    var newRow=document.getElementById("srow"+this.suggestIndex);
	    
	    newRow.style.backgroundColor="yellow";
	    
	    if (this.suggestDiv.scrollTop>newRow.offsetTop)
	    {
	        this.suggestDiv.scrollTop-=lineHeight;
	    }
	}
	
	this.select=function()
	{
		if (self.suggestIndex<0)
			return;
		var text=document.getElementById("srow"+this.suggestIndex).innerHTML;
		getControl(textboxId).value=text;
	}

    this.mouseSelect=function()
    {
        getControl(textboxId).value=this.innerHTML;
        self.divClose();
        getControl(textboxId).focus();
    }
    
    this.mouseOver=function()
    {
        this.style.backgroundColor="yellow";
    }
	this.mouseOut=function()
    {
        this.style.backgroundColor="#ffffff";
    }
	
	// checks whether a pressed key makes the current string
	// fall into a given prefix
	this.checkPrefix=function(keycode)
	{
	    var tbox=getControl(textboxId);
		var text=tbox.value;
		
		// first, we build the actual string with the last typed char
		text+=String.fromCharCode(keycode);
		text=text.toUpperCase();
		
		// then we require one of two cases:
		// either a given prefix begins with the resulting string
		// or the resulting string begins with one of the given prefixes
		var optionText;
		for (var k in optionsArray)
		{
		    if (withKey) optionText=optionsArray[k].split("##")[1].toUpperCase();
		    else optionText=optionsArray[k].toUpperCase();
		    
			if (optionText.indexOf(text)==0 || text.indexOf(optionText)==0)
                return true;
		}
		
		return false;
	}
	
	this.suggestPop2=function()
	{
		if (this.suggestIndex>-1)
		{
			document.getElementById("srow"+this.suggestIndex).style.backgroundColor="#ffffff";
		}
		this.suggestIndex=-1;
		
		var tbox=getControl(textboxId);
		var text=tbox.value;
		
		if (text=="" && suggestWhenEmpty==false)
		{
			if (self.suggestDiv!=null)
				self.divClose();
			return;
		}
	
		if (self.suggestDiv==null)
			self.divOpen();
	
		self.suggestDiv.innerHTML="";
		
		var ind=0; var exp;
		var show=false;
		var table=document.createElement("table");
		table.style.width="100%";
		table.cellSpacing="0";
		self.suggestDiv.appendChild(table);
		
		var optionText;
		for (var k in optionsArray)
		{
		    if (withKey) optionText=optionsArray[k].split("##")[1].toUpperCase();
		    else optionText=optionsArray[k].toUpperCase();
		    
			exp=optionText;
			if (exp.indexOf(text.toUpperCase())==0)
			{
			    if (document.all)
			        var row=table.insertRow();
			    else
			        var row=table.insertRow(table.rows.length);
			    
			    var cell=row.insertCell(0);
			    cell.id="srow"+ind;
			    cell.innerHTML=exp;
			    
			    cell.style.borderWidth="1px";
			    cell.style.borderStyle="solid";
			    cell.style.borderTopStyle="none";
			    cell.style.borderColor="#dddddd";
			    
				cell.onclick=self.mouseSelect;
				cell.onmouseover=self.mouseOver;
				cell.onmouseout=self.mouseOut;
				if (exp.length>text.length) show=true;
				ind++;
			}
		}
		self.maxIndex=ind-1;
		if (self.maxIndex<1 && !show)
		    self.divClose();
	}
	
	getControl(textboxId).onkeydown = this.suggestPop;
	getControl(textboxId).autocomplete="off";
	getControl(textboxId).onfocus=this.suggestPop;
	
	// we start by a divClose to get a value
	// possibly set at page load
	this.divClose();
}

// makes a control only partially editable
// useful for mandatory prefixes
function partiallyEditable(textboxId)
{
    var self=this;
    var tb=getControl(textboxId);
    var prefix="";
    
    this.setPrefix=function(pfx)
    {
        prefix=pfx;
    }
    
    this.checkPrefix=function()
    {
        if (tb.value.length<prefix.length ||
		    tb.value.substr(0, prefix.length)!=prefix)
		{
		    tb.value=prefix;
		}
    }
    
    this.onkeydown=function(e)
    {
        var keyCode=_getKey(e);
        setTimeout(tb.checkPrefix, 1);
    }
    
    tb.checkPrefix=this.checkPrefix;
    tb.onkeydown=this.onkeydown;
	tb.autocomplete="off";
}


// date control
function dateboxControl(textboxId)
{
	var self=this;
	var db=getControl(textboxId);
	var newField=false;
	var numbers="0123456789";
	var sleep=false;
	
	if (db.value=="")
	    db.value="00/00/0000";
	
	this.init=function()
	{
		sleep=false;
		self.setField(0);
		return false;
	}
	
	this.getCaretPos=function()
    {
		// To get cursor position, get empty selection range
	    var oSel = document.selection.createRange ();
		// Move selection start to 0 position
		oSel.moveStart('character', -db.value.length);
		// The caret position is selection length
		return oSel.text.length;
	};

	this.setCaretPos=function (iCaretPos, selWi) {
		// Create empty selection range
		var oSel = document.selection.createRange ();
		// Move selection start and end to desired position
		oSel.moveStart ('character', -10);
		oSel.collapse();
		oSel.moveStart ('character', iCaretPos);
		// oSel.moveEnd ('character', -10);
		oSel.moveEnd ('character', selWi);
		oSel.select ();
		selLength=selWi;
	};
	
	this.getField=function()
	{
		var field=0;
		var value=db.value;
		var pos=self.getCaretPos();
		for (var k=pos; k<value.length; k++)
			if (value.charAt(k)=="/") field++;
		field=2-field;
		return field;
	};
	
	this.setField=function(field)
	{
		var value=db.value;
		var sl1=value.indexOf("/")+1;
		var sl2=value.lastIndexOf("/")+1;		
		if (field==0)
			self.setCaretPos(0,0);
		if (field==1)
			self.setCaretPos(sl1,0);
		if (field==2)
			self.setCaretPos(sl2,0);	
	    self.selectPart();
	};
	
	this.selectPart=function()
	{
		// if (sleep)
		//	return false;

		var pos=self.getCaretPos();
		var value=db.value;
		for (var start=pos; start>0; start--) 
			if (value.charAt(start)=="/") 
			{
				start++;
				break;
			}
		for (var end=pos; end<value.length-1; end++)
			if (value.charAt(end)=="/")
			{
				end--;
				break;
			}
		self.setCaretPos(start, end-start+1);
		newField=true;
		sleep=false;
	};
	
	this.fieldStartPos=function(field)
	{
		var pos=0;
		var exp=db.value.split("/");
		for (k=0; k<field; k++)
			pos+=exp[k].length;
		return pos+field;
	}
	
	this.onkeydown=function(e)
	{
		var keyCode=_getKey(e);
		var pos=self.getCaretPos();
		var value=db.value;
		
		if (key_blockKeys!="")
			return false;
		
		var field=self.getField();
		var exp=db.value.split("/");
		
		if (keyCode==8)
		{
		    newField=false;
			var pos=self.getCaretPos();
			if (exp[field].length>0)
				exp[field]=exp[field].substr(0, exp[field].length-1);
			else
				keyCode=37;
			if (keyCode==8)
			{
				db.value=exp.join("/");
				// alert(self.fieldStartPos(field));
				self.setCaretPos(exp[field].length+self.fieldStartPos(field), 0);
			    // self.setField(field);
			    _cancelKeyEvent(e);
				sleep=false;
				return false;
			}
		}
		if (keyCode==38)
		{
			sleep=false;		    
			exp[field]=exp[field]*1+1;
			if (field==0 && exp[field]>31) exp[field]=0;
			else if (field==1 && exp[field]>12) exp[field]=0;
			if ((""+exp[field]).length<2) exp[field]="0"+exp[field];
			db.value=exp.join("/");
		    self.setField(field);
			return false;
		}
		if (keyCode==40)
		{
			sleep=false;
			exp[field]=exp[field]*1-1;
			
			if (field==0 && exp[field]<0) exp[field]=31;
			else if (field==1 && exp[field]<0) exp[field]=12;
			else if (field==2 && exp[field]<0) exp[field]=1999;

			if ((""+exp[field]).length<2) exp[field]="0"+exp[field];
			db.value=exp.join("/");
		    self.setField(field);
			return false;
		}
		if (keyCode==37)
		{
			sleep=false;
			if (exp[field]=="")
				if (field<2)
					exp[field]="00";
				else
					exp[field]="0000";
			db.value=exp.join("/");
			
			field--;
			if (field<0) field=0;
		    self.setField(field);
		    _cancelKeyEvent(e);
			return false; 
		}
		if (keyCode==39)
		{
			sleep=false;
			if (exp[field]=="")
				if (field<2)	
					exp[field]="00";
				else
					exp[field]="0000";
			db.value=exp.join("/");
			
			field++;
			if (field>2) field=2;
		    self.setField(field);
			return false;
		}
		if (keyCode==46)
		{
			sleep=false;
		    newField=true;
		    self.selectPart();
		    _cancelKeyEvent(e);
			db.value="00/00/0000";
			self.setField(0);
			return false;
		}
		return true;
	};
	
	this.onkeypress=function(e)
	{
		var keyCode=_getKey(e);
	    var ch=String.fromCharCode(keyCode);
		var selStart=self.getCaretPos()-selLength;
		var string=db.value;
		var exp=string.split("/");
		
	    var field=self.getField();
		
		if (sleep)
			return false;
		
		if (ch=="/")
		{
			self.setField(field+1);
			return false;
		}
		
		if (numbers.indexOf(ch)<0)
			return false;
		
		if (field<2 && exp[field].length==2) exp[field]="";
		if (field==2 && exp[field].length==4) exp[field]="";
		
		if (newField==true)
			exp[field]=ch;
		else
			exp[field]+=ch;
		
		newField=false;
		
		var newStart=selStart+1;
		var newWidth=exp[field].length;
		
		db.value=exp.join("/");
		
		if (field<2 && exp[field].length==2)
		{
			self.setField(field+1);
			return false;
		}
		if (field==2 && exp[field].length==4)
		{
			self.setField(2);
			// self.exit();
			sleep=true;
			return false;
		}
		newWidth=0;

		self.setCaretPos(newStart, newWidth);
		return false;
	};
	
	this.exit=function()
	{
	    document.selection.empty();
		var exp=db.value.split("/");
		
		if (exp[2]=="")
			exp[2]="0000";
		
        if (exp[0]*1==0 && exp[1]*1==0 && exp[2]*1==0)
		{
			db.value="00/00/0000";
            return;
	    }
	    
		while (exp[0].length<2) exp[0]="0"+exp[0];
	    while (exp[1].length<2) exp[1]="0"+exp[1];
	    if (exp[2]>30 && exp[2]<100 && exp[2]!="0000") exp[2]=exp[2]*1+1900;
	    else if (exp[2]<100 && exp[2]!="0000") exp[2]=exp[2]*1+2000;
	    db.value=exp.join("/"); 
	}
	
	db.onfocus=this.init;
	db.onclick=this.selectPart;
	db.onkeypress=this.onkeypress;
	db.onkeydown=this.onkeydown;
	db.onblur=this.exit;
}


// -------------------------------------------------------
// Tabber control

function tabber(panelIds, tabIds, unselTabClass, selTabClass, disableDivElements, statusFieldId)
{
    var panels=panelIds.split("##");
    var tabButtons=tabIds.split("##");
    var self=this;
    var currentTab=0;
    
    if (statusFieldId!=null && statusFieldId!=undefined)
        if (getControl(statusFieldId).value!="")
            currentTab=getControl(statusFieldId).value;
    
    self.hideAll=function()
    {
        for (var x=0; x<panels.length; x++)
        {
            document.getElementById(panels[x]).style.display="none";
            document.getElementById(tabButtons[x]).className=unselTabClass;
            if(disableDivElements == true)
            {
                disableForm(panels[x], true);
            }
        }
    };
    
    self.showPanel=function(panelNum)
    {
        self.hideAll();
        document.getElementById(panels[panelNum]).style.display="block";
        document.getElementById(tabButtons[panelNum]).className=selTabClass;
        enableForm(panels[panelNum], false);
        currentTab=panelNum;
    };
    
    self.getTabClick=function()
    {
        var panelNum=this.tabNumber;
        if(currentTab!=panelNum)
        {
            self.showPanel(panelNum);
        }
        currentTab=panelNum;

        if (statusFieldId!=null && statusFieldId!=undefined)
            getControl(statusFieldId).value=currentTab;
    };
    
    for (var x=0; x<tabButtons.length; x++)
    {
        var tab=document.getElementById(tabButtons[x]);
        tab.tabNumber=x;
        tab.onclick=self.getTabClick;
    }
    
    self.showPanel(currentTab);
}

// FORM METHODS

// disables a form
// disables all active elements inside a container element
// and the element itself.
// if onlyBlock is true the contents aren't erased
function disableForm(containerName, onlyBlock)
{
    var formMembers=getControlsArray(containerName);
    
    if (formMembers==null)
        return;
    
    // disabling of single elements
    for (var k=0; k<formMembers.length; k++)
    {
        var member=getControl(formMembers[k]);
        
        if (member==null) 
            continue;
            
        if (member.type=="select-one" || member.type=="text" || member.type=="checkbox")
        {
            if (onlyBlock==true)
                blockControl(formMembers[k]);
            else
                disableControlTabber(formMembers[k]);
        }
    }
    
    // disabling of parent element
    var container=getControl(containerName);
    if(container!=null)
        container.disabled=true;
    
    // code for managing a curtain
    // var curtain=getControl(curtain);
    // var curtainEnd=getControl(curtainEnd);

    // curtain.style.zIndex=10;
    // curtain.style.backgroundColor="#ffaaaa";

    // curtain.style.pixelWidth="730";
    // curtain.style.pixelHeight=curtainEnd.offsetTop-curtain.offsetTop;
}

function enableForm(containerName, onlyBlock)
{
    var formMembers=getControlsArray(containerName);
    
    if (formMembers==null)
        return;
    
    // enabling of single elements
    for (var k=0; k<formMembers.length; k++)
    {
        var member=getControl(formMembers[k]);
        
        if (member==null) 
            continue;
            
        if (member.type=="select-one" || member.type=="text" || member.type=="checkbox")
        {
            enableControlTabber(formMembers[k]);
        }
    }
    
    // disabling of parent element
    var container=getControl(containerName);
    if(container!=null)
    container.disabled=false;
    
    // code for managing a curtain
    // var curtain=getControl(curtain);
    // var curtainEnd=getControl(curtainEnd);

    // curtain.style.zIndex=10;
    // curtain.style.backgroundColor="#ffaaaa";

    // curtain.style.pixelWidth="730";
    // curtain.style.pixelHeight=curtainEnd.offsetTop-curtain.offsetTop;
}

function getControlsArray(container)
{
    var result=new Array();
    if (typeof(container)=='string')
        container=getControl(container);
     
    goThroughDOM(container, result);
    return result;
}

function goThroughDOM(parentObj, result)
{
    if (parentObj==null)
        return;

    for (var i=0; i<parentObj.childNodes.length; i++) 
    {
        var childObj = parentObj.childNodes[i];
        if (childObj.id!=null && childObj.id!=undefined && childObj.id!="") 
        {
            result.push(childObj.id);
        }
        goThroughDOM(childObj, result);
    }
}

function enableControlTabber(srvId)
{
    var control=getControl(srvId);
    control.disabled=false;
    control.readOnly = false;
    if(control.type!="submit")
    {
        control.style.backgroundColor = "#FFFFFF";
    }
}

// this function disables a control ERASING its content
function disableControlTabber(srvId)
{
    var control=getControl(srvId);
    control.disabled=true;
    control.readOnly = true;
    if(control.type!="submit")
    {
    control.style.backgroundColor="#EFEFEF";
    control.value="";
        control.checked=false;
    }
}

// this function blocks a control WITHOUT erasing its content
function blockControl(srvId)
{
    var control=getControl(srvId);
    control.disabled=true;
    control.readOnly = true;
    if(control.type!="submit")
    {
        control.style.backgroundColor="#EFEFEF";
    }
}
