/*
**		Common.js
**
**
*/

/*	This is taken from phpMyAdmin, parts tweaked for our needs.
 */

/**
 * This array is used to remember mark status of rows in browse mode
 */
var marked_row = new Array;



/**
 * Sets/unsets the pointer and marker in browse mode
 *
 * @param   object    the table row
 * @param   interger  the row number
 * @param   string    the action calling this script (over, out or click)
 * @param   string    the default background color
 * @param   string    the color to use for mouseover
 * @param   string    the color to use for marking a row
 *
 * @return  boolean  whether pointer is set or not
 */
function setPointer(theRow, theRowNum, theAction, theDefaultClass, thePointerClass, theMarkClass, searchMainRow)
{
	/*  pataki@dsd.sztaki.hu:
	 *
	 *	If setPointer() is called from a spanned row we need to search for a row called
	 *	main_row_SOME_INDEX
	 *
	 *	Mozilla does things a little bit conservatively: the white spaces between TR-s are
	 *	also 'previousSibling'-s to TR nodes. For explorer the siblings to a TR are always
	 *	TR.
	 */
	if (searchMainRow) {
		prevRow = theRow;
		while (true) {
			while (prevRow.nodeType == 3) {
				prevRow = prevRow.previousSibling;
			}
			if (prevRow.id && prevRow.id.indexOf('main_row') < 0)
				prevRow = prevRow.previousSibling;
			else
				break;

		}
		theRow = prevRow;
	}


    var theCells = null;


    // 1. Pointer and mark feature are disabled or the browser can't get the
    //    row -> exits
    if ((thePointerClass == '' && theMarkClass == '')
        || typeof(theRow.style) == 'undefined') {
        return false;
    }
    // 2. Gets the current row and exits if the browser can't get it
    if (typeof(document.getElementsByTagName) != 'undefined') {
        theCells = theRow.getElementsByTagName('td');
    }
    else if (typeof(theRow.cells) != 'undefined') {
        theCells = theRow.cells;
    }
    else {
        return false;
    }

    // 3. Gets the current color...
    var rowCellsCnt  = theCells.length;
    var domDetect    = null;
    var currentClass = null;
    var newClass     = null;
    // 3.1 ... with DOM compatible browsers except Opera that does not return
    //         valid values with "getAttribute"
    if (typeof(window.opera) == 'undefined'
        && typeof(theCells[0].getAttribute) != 'undefined') {
        currentClass = theCells[0].getAttribute('class');
        domDetect    = true;
    }
    // 3.2 ... with other browsers
    else {
        currentClass = theCells[0].className;
        domDetect    = false;
    } // end 3

	// pataki@ : bugfix for Mozilla
	if (!currentClass)
		currentClass = "";

    // 4. Defines the new color
    // 4.1 Current color is the default one
    if (currentClass == ''
        || currentClass.toLowerCase() == theDefaultClass.toLowerCase()) {
        if (theAction == 'over' && thePointerClass != '') {
            newClass              = thePointerClass;
        }
        else if (theAction == 'click' && theMarkClass != '') {
            newClass              = theMarkClass;
        }
    }
    // 4.1.2 Current color is the pointer one
    else if (currentClass.toLowerCase() == thePointerClass.toLowerCase()
             && (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])) {
        if (theAction == 'out') {
            newClass              = theDefaultClass;
        }
        else if (theAction == 'click' && theMarkClass != '') {
            newClass              = theMarkClass;
            marked_row[theRowNum] = true;
        }
    }
    // 4.1.3 Current color is the marker one
    else if (currentClass.toLowerCase() == theMarkClass.toLowerCase()) {
        if (theAction == 'click') {
            newClass              = (thePointerClass != '')
                                  ? thePointerClass
                                  : theDefaultClass;
            marked_row[theRowNum] = (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])
                                  ? true
                                  : null;
        }
    } // end 4
    // 5. Sets the new color...
    if (newClass) {
        var c = null;
        // 5.1 ... with DOM compatible browsers except Opera
        if (domDetect) {
            for (c = 0; c < rowCellsCnt; c++) {
               	 theCells[c].setAttribute('class', newClass, 0);
            } // end for
        }
        // 5.2 ... with other browsers
        else {
            for (c = 0; c < rowCellsCnt; c++) {
                theCells[c].clasName = newClass;
            }
        }
    } // end 5

	/*	pataki@dsd.sztaki.hu:
	 *	If there's a row spanned TD in this row, then collect the spanned rows and
	 *	color them. (Here we take care of Mozilla vs Explorer DOM differences)
	 */
    if (theCells[0].rowSpan > 1) {
    	nextTR = theRow;
    	for (i=1; i<theCells[0].rowSpan; i++) {
       		nextTR = nextTR.nextSibling;
       		while (nextTR.nodeType == 3) {
				nextTR = nextTR.nextSibling;
			}
       		setPointer(nextTR, theRowNum+i, theAction, theDefaultClass, thePointerClass, theMarkClass);
       	}

    }

    return true;
} // end of the 'setPointer()' function


/**
 * Sets/unsets the pointer and marker in browse mode
 *
 * @param   object    the table row
 * @param   interger  the row number
 * @param   string    the action calling this script (over, out or click)
 * @param   string    the default background color
 * @param   string    the color to use for mouseover
 * @param   string    the color to use for marking a row
 *
 * @return  boolean  whether pointer is set or not
 */
function setResultPointer(theRow, theRowNum, theAction, theDefaultClass, thePointerClass, theMarkClass, searchMainRow)
{

	/*  pataki@dsd.sztaki.hu:
	 *
	 *	If setPointer() is called from a spanned row we need to search for a row called
	 *	main_row_SOME_INDEX
	 *
	 *	Mozilla does things a little bit conservatively: the white spaces between TR-s are
	 *	also 'previousSibling'-s to TR nodes. For explorer the siblings to a TR are always
	 *	TR.
	 */
	origRow = theRow;
	if (searchMainRow) {
		prevRow = theRow;
		while (true) {
			while (prevRow.nodeType == 3) {
				prevRow = prevRow.previousSibling;
			}
			if (prevRow.id && prevRow.id.indexOf('main_row') < 0)
				prevRow = prevRow.previousSibling;
			else
				break;

		}
		theRow = prevRow;
	}


    var theCells = null;
	//alert('thePointerClass: '+thePointerClass+' | theMarkClass:'+theMarkClass+' | theRow.style: '+theRow.style);

    // 1. Pointer and mark feature are disabled or the browser can't get the
    //    row -> exits
    if ((thePointerClass == '' && theMarkClass == '')
        || typeof(theRow.style) == 'undefined') {
        return false;
    }


    // 2. Gets the current row and exits if the browser can't get it
    if (typeof(document.getElementsByTagName) != 'undefined') {
    	/*	Select only the left column and only one meaning from the right column.
    	 */
    	if (origRow != theRow) {
    		theCells = new Array();
    		theCells[theCells.length] = theRow.getElementsByTagName('td')[0];
    		theCells[theCells.length] = origRow.getElementsByTagName('td')[0];
    	}
    	else {
        	theCells = theRow.getElementsByTagName('td');
    	}
    }
    else if (typeof(theRow.cells) != 'undefined') {
        theCells = theRow.cells;
    }
    else {
        return false;
    }

    // 3. Gets the current color...
    var rowCellsCnt  = theCells.length;
    var domDetect    = null;
    var currentClass = null;
    var newClass     = null;
    /*
    // 3.1 ... with DOM compatible browsers except Opera that does not return
    //         valid values with "getAttribute"
    if (typeof(window.opera) == 'undefined'
       && typeof(theCells[0].getAttribute) != 'undefined') {
        currentClass = theCells[0].getAttribute('class');
        domDetect    = true;
    }
    // 3.2 ... with other browsers
    else {
        currentClass = theCells[0].className;
        domDetect    = false;
    } // end 3
	*/

	/*	pataki@: We expect a DOM enabled browser
	 */
	currentClass = theCells[0].className;
	domDetect    = false;

	// pataki@ : bugfix for Mozilla
	if (!currentClass)
		currentClass = "";

    // 4. Defines the new color
    // 4.1 Current color is the default one
    if (currentClass == ''
        || currentClass.toLowerCase() == theDefaultClass.toLowerCase()) {
        if (theAction == 'over' && thePointerClass != '') {
            newClass              = thePointerClass;
        }
        else if (theAction == 'click' && theMarkClass != '') {
            newClass              = theMarkClass;
        }
    }
    // 4.1.2 Current color is the pointer one
    else if (currentClass.toLowerCase() == thePointerClass.toLowerCase()
             && (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])) {
        if (theAction == 'out') {
            newClass              = theDefaultClass;
        }
        else if (theAction == 'click' && theMarkClass != '') {
            newClass              = theMarkClass;
            marked_row[theRowNum] = true;
        }
    }
    // 4.1.3 Current color is the marker one
    else if (currentClass.toLowerCase() == theMarkClass.toLowerCase()) {
        if (theAction == 'click') {
            newClass              = (thePointerClass != '')
                                  ? thePointerClass
                                  : theDefaultClass;
            marked_row[theRowNum] = (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])
                                  ? true
                                  : null;
        }
    } // end 4

    // 5. Sets the new color...
    if (newClass) {
        var c = null;
        // 5.1 ... with DOM compatible browsers except Opera
        if (domDetect) {
            for (c = 0; c < rowCellsCnt; c++) {
               	 theCells[c].setAttribute('class', newClass, 0);
            } // end for
        }
        // 5.2 ... with other browsers
        else {
            for (c = 0; c < rowCellsCnt; c++) {
                theCells[c].className = newClass;
            }
        }
    } // end 5


    return true;
} // end of the 'setResultPointer()' function


var loaded = false;

/* 2.5.6:
if (DynAPI) {
	DynAPI.onLoad=function() {
		loaded = true;
	}
}
*/


var timerID;
if (DynAPI) {
	function markLoaded () {
		loaded = true;
		//dynapi.document.insertAllChildren();
	}

	DynAPI.onLoad(markLoaded);

	// Compatibility with 2.5.6
	is = DynAPI.ua;

	// Popup panel must be created before the page is loaded otherwise
	// it won't work with Opera.
	// Tdere's also a
	//	dynapi.document.insertAllChildren();
	// call in the <body>, which is required by Opera
	createPopupPanel();
}

function
createPopupPanel()
{
	popupPanel = new LoadPanel();
	if (is.ns && popupPanel.useILayer) { // 2.5.6
		popupPanel.useILayer(true);
		popupPanel.setSize(10,10); // height will be overwritten by default
	}
	else {
		popupPanel.setAutoSize(10,10); // height will be overwritten by default
	}

	// Resize after content is loaded
	if (popupPanel.setAutoResizeWidth && popupPanel.setAutoResizeHeight) { // 2.5.6
		popupPanel.setAutoResizeWidth(true);
		popupPanel.setAutoResizeHeight(true);
	}
	popupPanel.setVisible(false);
	DynAPI.document.addChild(popupPanel);
}

function
hidePron()
{
	if (timerID)
		clearTimeout(timerID);
	if (popupPanel) {
		// Mozilla needs a not too empty HTML to clear the content.
		// In other browsers popupPanel.clear() is OK.
		if (is.ns) {
			popupPanel.setVisible(false);
			popupPanel.setURL("pron/searchpron.php?clear=true");
		}
		else {
			popupPanel.clear();
		}
		//DynAPI.document.removeChild(popupPanel);
		//popupPanel = null;
	}
}

function
popupPron(event,layer,word,lang)
{
	// Popup pronunciation is available only when all of the page is
	// loaded
	if (!loaded)
		return;

	if (timerID)
		clearTimeout(timerID);

	if (event) {
		if (event.clientY) {
			x = event.clientX;
			y = event.clientY;
		}
		else {
			x = event.x;
			y = event.y;
		}
		if (is.ns) {
			// ns4's event already contains the offset, ns6 doesn't
			if (is.ns4) {
				xoffset = 0;
				yoffset = 0;
			}
			else {
				xoffset = window.pageXOffset
				yoffset = window.pageYOffset
			}
		}
		else {
			xoffset = window.document.body.scrollLeft
			yoffset = window.document.body.scrollTop
		}
		//alert('xoffset: '+xoffset+' - yoffset: '+yoffset);
        //alert('x: '+x+' - y: '+y);

		x += xoffset;
		y += yoffset;
	}

	if (!popupPanel) {
		createPopupPanel();
	}
	//popupPanel.setAutoSize(10,10); // height will be overwritten by default

	//popupPanel.setHTML("Loading pronounciation ...");

	if (popupPanel.moveTo) { 	// 2.5.6
		popupPanel.moveTo(x+10,y+10);
	}
	else {				// 3.0.0
		popupPanel.setLocation(x+10,y+10);
	}
	timerID = setTimeout('loadPron("pron/searchpron.php?des=sztaki_origo&lang='+lang+'&word='+escape(word)+'")', 1000);
}

function
loadPron(url)
{
	popupPanel.setURL(url);
	popupPanel.setVisible(true);
}

/*	Right-click context menu needs to listen to onmousedown events
	*	through DynAPI now.
	*/
if (DynAPI) {
	// DynAPI 2.5.6
	/*
	if (EventListener) {
		var el = new EventListener();
		el.onmousedown = function(e) {
			hideContextMenu(e);
		}
	}
	*/
	// DynAPI 3.0.0
	var el = {
		onmousedown:function(e) {
			hideContextMenu(e);
		}
	}

	DynAPI.document.addEventListener(el);
}

function isdefined(variable) { if(typeof(variable) !="undefined") return true; else return false; }



/*
hb
                   *****************************************
                   **                                     **
                   **                                     **
                   **     c o n t e x t m e n u . j s     **
                   **                                     **
                   **                                     **
                   *****************************************


	COPYRIGHT (C):  2001, MTA SZTAKI Distributes Systems Department, Hungary
	AUTHOR:		   	Balazs E. Pataki (beep); (e-mail: balazs.pataki@sztaki.hu)
	CREATED:		Thu Dec 13 18:19:13 GMT+0100 2001

	TITLE:			Right-Click Context Sensitive Menu

	CHANGES:

*/

/* Addition by Gellert Gyuris. Thanks!
 */
function geckoGetRv() {
	var rvValue = 0;
	var product = new String( navigator.product ).toLowerCase()
	if ( product != "gecko" ) return rvValue;

	var ua = navigator.userAgent.toLowerCase()
	var rvStart = ua.indexOf('rv:');
	var rvEnd   = ua.indexOf(')', rvStart);
	var rv      = ua.substring(rvStart+3, rvEnd);
	var rvParts = rv.split('.');
	var exp     = 1;
	for ( var i = 0; i < rvParts.length; i++ ) {
		var val = parseInt( rvParts[i] );
		rvValue += val / exp;
		exp *= 100;
	}
	return rvValue;
}

function showMenu (evt, correctionLink, correctionCaption, newMeaningLink, newMeaningCaption)
{


	// Correction ...
	html = '<div id="contextMenuItemDiv" style="width:100%" onmouseover="handleOver(this,event)" onmouseout="handleOut(this,event)" onmousedown="return gotoLink(this, event)">&nbsp;&nbsp;<nobr><a id="contextMenuItemLink" CLASS="menu" style="text-decoration: none; netscape47: suxx" href="'+correctionLink+'" onmousedown="return gotoLink(this, event)" target="_top">'+correctionCaption+' ... </a></nobr></div>';

	// New meaning ...
	html += '<div id="contextMenuItemDiv2" style="width:100%" onmouseover="handleOver(this,event)" onmouseout="handleOut(this,event)" onmousedown="return gotoLink(this, event)">&nbsp;&nbsp;<nobr><a id="contextMenuItemLink2" CLASS="menu" style="text-decoration: none; netscape47: suxx" href="'+newMeaningLink+'" onmousedown="return gotoLink(this, event)" target="_top">'+newMeaningCaption+' ...</a></nobr></div>';

	if (document.all) {
		if (evt.type != 'contextmenu')
			return true;

		//	IE5
		//
		var rightedge = document.body.clientWidth-event.clientX;
		var bottomedge = document.body.clientHeight-event.clientY;
		var iemenu = document.all.contextMenu;
		if (rightedge < iemenu.offsetWidth)
			iemenu.style.left = document.body.scrollLeft + event.clientX - iemenu.offsetWidth;
		else
			iemenu.style.left = document.body.scrollLeft + event.clientX;
		if (bottomedge < iemenu.offsetHeight)
			iemenu.style.top = document.body.scrollTop + event.clientY - iemenu.offsetHeight;
		else
			iemenu.style.top = document.body.scrollTop + event.clientY;
		//document.all.contextMenu.style.pixelLeft = event.clientX;
		//document.all.contextMenu.style.pixelTop = event.clientY;
		iemenu.style.visibility = 'visible';
		iemenu.innerHTML = html;
		return false;
	}
	else if (document.layers) {
		//	NS 4.x
		//
		var nsmenu = document.contextMenu;
		nsmenu.document.open();
		// Bloody netscape forgets about the border of contextMenu, so
 		// we have to create one "by hand". Grrrr.
		nsmenu.document.writeln('<div style="border: 2px outset white">'+html+'</div>');
		nsmenu.document.close();

		if (evt.which == 3) {
			nsmenu.left = evt.x;
      		nsmenu.top = evt.y;
			nsmenu.visibility = 'show';
			return false;
		}
	}
	else if ((ns6menu = document.getElementById('contextMenu'))) {
		if (evt.type != 'contextmenu')
			return true;

		// It works similar to ie5 only the naming is different. Here we fall
		//	back to ie5 naming conventions and use the same .left and .top
		//	calculation algorithm.
		//

		/* Addition by Gellert Gyuris. Thanks!
		 */
		if ( geckoGetRv() < 0.0908 ) {
			document.body.clientWidth = document.width;
			document.body.clientHeight = document.height;
			document.body.scrollLeft = window.scrollX;
			document.body.scrollTop = window.scrollY;
		}

		x = evt.clientX;
		y = evt.clientY;
		xoffset = window.pageXOffset;
		yoffset = window.pageYOffset;

		x += xoffset;
		y += yoffset;

		//alert('left: '+ns6menu.style.left+' - top:'+ns6menu.style.top);
		//alert('x: '+x+' - y:'+y);
		ns6menu.style.left = x+"px";
		ns6menu.style.top = y+"px";
		ns6menu.innerHTML = html;
		ns6menu.style.position = 'absolute';
		ns6menu.style.visibility = 'visible';
		return false;
	}
	return true;
}

/*	Note: if DynAPI is used, it will override this handle. It is taken care of
 *	later.
 */
document.onmousedown = hideContextMenu;

function
hideContextMenu(evt)
{
	if (document.all)
		document.all.contextMenu.style.visibility = 'hidden';
	else if (document.layers)
		document.contextMenu.visibility = 'hidden';
	else
		document.getElementById('contextMenu').style.visibility = 'hidden';
	return true;
}

function
handleOver(elem, evt)
{
	_handleOverOut('menuOn', elem, evt);
}

function
handleOut(elem, evt)
{
	_handleOverOut('menu', elem, evt);
}

function
_handleOverOut(kind, elem, evt)
{
	elem.className = kind;

	// contextMenuItemDiv or contextMenuItemDiv1, contextMenuItemDiv2, etc
	//
	if (elem.id.indexOf('contextMenuItemDiv') != -1) {
		if (elem.id.length > 'contextMenuItemDiv'.length) {
			theID = "contextMenuItemLink"+elem.id.substr('contextMenuItemDiv'.length);
		}
		else {
			theID = "contextMenuItemLink";
		}
		if (document.all) {
			itemLink = eval("document.all."+theID);
			itemLink.className = elem.className
		}
		else if((itemLink = document.getElementById(theID)))
			itemLink.className = elem.className;
	}
	else {
		if (elem.id.length > 'contextMenuItemLink'.length) {
			theID = "contextMenuItemDiv"+elem.id.substr('contextMenuItemLink'.length);
		}
		else {
			theID = "contextMenuItemDiv";
		}

		if (document.all){
			itemDiv = eval("document.all."+theID);
			itemDiv.className = elem.className
		}
		else if((itemDiv = document.getElementById(theID)))
			itemDiv.className = elem.className;
	}

}

function
gotoLink(elem, evt)
{
	if (elem.id.indexOf('contextMenuItemDiv') != -1) {
		if (elem.id.length > 'contextMenuItemDiv'.length) {
			theID = "contextMenuItemLink"+elem.id.substr('contextMenuItemDiv'.length);
		}
		else {
			theID = "contextMenuItemLink";
		}

		if (document.all) {
			itemLink = eval("document.all."+theID);
			href = itemLink.href;
		}
		else if ((itemLink = document.getElementById(theID)))
			href = itemLink.href;
		window.top.location.href = href;
		return false;
	}
	else
		return true;
}


var correctionUpDownEvents = {};
correctionUpDownEvents.onmouseup = correctionUpDownEvents.onmousedown = function(e) {
	var o = e.getSource();

	var bc = e.getBubbleChild();
	var bcs = bc? ' bubbleChild=' + bc.name : '';

	e.defaultValue = returnVal;

	alert(e.type+' '+o.name+' xy='+e.x+','+e.y+' pXY='+e.pageX+','+e.pageY + ' origin=' + e.getOrigin().name + bcs);
}



/*
**	Form related functions.
**
**
**
**/


/*	Switch state of the checkbox `triggerName'
 */
function
switchCheck (
	triggerName)
{
	trigger_from_input = eval ('document.forms.search.'+triggerName);

	trigger_from_input.checked = !trigger_from_input.checked;
	trigger_from_input.value = trigger_from_input.checked+0;

	if (triggerName == "F") {
		switchFrameNoframe (trigger_from_input.checked)
	}
	selectWordInField();
	return false;
}

/*	Clear status line
 */
function
clearStatus (
	triggerName)
{
	window.status = "";
	return true;
}

function
switchImages()
{
	left_width = document.images['left'].width;
	left_height = document.images['left'].height;
	left_src = document.images['left'].src;
	document.images['left'].src = document.images['right'].src;
	document.images['left'].width = document.images['right'].width;
	document.images['left'].height = document.images['right'].height;
	document.images['right'].src = left_src;
	document.images['right'].width = left_width;
	document.images['right'].height = left_height;

	curr_left_src = document.images['left'].src;
}


function
join (
	sep,
	arr)
{
	var s = "";
	for (var i=0; i<arr.length; i++) {
		s += arr[i];
		if (i+1 != arr.length)
			s += sep;
	}
	return s;
}

function
submitForm()
{
	document.forms["search"].submit();
	selectWordInField();
	return false;
}

function
selectWordInField()
{
	if (document.forms["search"].W.createTextRange) {
		r = document.forms["search"].W.createTextRange();
		r.select();
	}
	else {
		document.forms["search"].W.select();
	}
	document.forms["search"].W.focus();
}

function
resetForm()
{
	document.forms["search"].reset();
	// this can have some non empty value, take care:
	document.forms["search"].W.value = "";
	selectWordInField();
	return false;
}

function
completeURLWithL (
	urlPart)
{
	return urlPart+"&L=" + escape (document.forms['search'].L.value);
}

function
jumpToCompletedURL (
	urlPart)
{
	window.top.location.href = completeURLWithL (urlPart);
	return false;
}

/*	Key press handling.
 *	NS 4, 6+ and IE supported.
 */
var searchButtonFocused = null;

function
getEvent(e)
{
	if( !e) {
        //if the browser did not pass the event information to the
        //function, we will have to obtain it from the event register
        if( window.event ) {
            //DOM
            e = window.event;
        } else {
            //TOTAL FAILURE, WE HAVE NO WAY OF REFERENCING THE EVENT
            e = -1;
        }
    }
    return e;
}

function
getKeyCode(e)
{
    if( typeof( e.which ) == 'number' ) {
        //NS 4, NS 6+, Mozilla 0.9+, Opera
        k = e.which;
    } else {
        if( typeof( e.keyCode ) == 'number'  ) {
            //IE, NS 6+, Mozilla 0.9+
            k = e.keyCode;
        } else {
            //TOTAL FAILURE, WE HAVE NO WAY OF OBTAINING THE KEY CODE
            k = -1;
        }
    }

    return k;
    //window.alert('The key pressed has keycode ' + e +
    //   ' and is key ' + String.fromCharCode( e ) );

}

function
getModifiers(e)
{
	var modifiers = new Object();

	if (e.modifiers) {
     modifiers.alt = e.modifiers & Event.ALT_MASK;
     modifiers.control = e.modifiers & Event.CONTROL_MASK;
     modifiers.shift = e.modifiers & Event.SHIFT_MASK;
     modifiers.meta = e.modifiers & Event.META_MASK;
  } else if (e.altKey || e.shiftKey || e.ctrlKey) {
     modifiers.alt = e.altKey;
     modifiers.control = e.ctrlKey;
     modifiers.shift = e.shiftKey;
     modifiers.meta = false;
  }

	return modifiers;
}

function
handleKeyDown(event)
{
	event = getEvent(event);
	keyCode = getKeyCode(event);
	key = String.fromCharCode(keyCode);
	modifiers = getModifiers(event);

	//alert(document.forms.search.W.value);
	if (searchButtonFocused && (keyCode == 13 || keyCode == 10)) {
		return false;
	}
	/*	Keypad '+', '-'
	 */
	else if (is_ie && (keyCode == 107 || keyCode == 109)) {
		//event.preventBubble();
		//event.stopPropagation();
		event.cancelBubble = true;
		changeDirection();
		return true;
	}
	/* left: 39, right: 37
	*/
	else if (keyCode == 37 && modifiers.shift) {
		event.cancelBubble = true;
		changeDirection();
		return false;
	}
	else if (keyCode == 39 && modifiers.shift) {
		event.cancelBubble = true;
		changeDirection();
		return false;
	}
	return true;
}

function
handleKeyUp(event)
{
	event = getEvent(event);
	keyCode = getKeyCode(event);
	modifiers = getModifiers(event);

    //key = String.fromCharCode(keyCode).toLowerCase();
	if (searchButtonFocused && (keyCode == 13 || keyCode == 10)) {
		submitForm();
		return false;
	}
	//alert(keyCode);
	return true;
}

document.onkeydown = handleKeyDown;
document.onkeyup = handleKeyUp;

// HP logo handling functions
var oldDocumentMouseOver;

function
showHPSWFLogo()
{
	var hp_logo_movie = document.getElementById("hp_logo_movie");
	if (hp_logo_movie.style.display == "inline")
		return;

	var hp_logo_a = document.getElementById("hp_logo_a");
	hp_logo_a.style.display="none";
	hp_logo_movie.style.display="inline";

	//oldDocumentMouseOver = document.body.onmouseover;
	//setTimeout("document.body.onmouseover = showHPIMGLogo", 50);
}

function
showHPIMGLogo()
{
	document.body.onmouseover = oldDocumentMouseOver;
	var hp_logo_a = document.getElementById("hp_logo_a");
	hp_logo_a.style.display = "inline";

	var hp_logo_movie = document.getElementById("hp_logo_movie");
	hp_logo_movie.style.display = "none";
}

// The link at the currently active hallatlan display
var activeHallatlanLink;
var _currentDomain;

/*	Similar to dojo.graphics.htmlEffects.wipeIn, but with fixes for Opera and KHTML
 */
function
wipeInSWF(node, duration, callback, dontPlay)
{
	node = dojo.byId(node);
	var savedHeight = dojo.html.getStyle(node, "height");
	dojo.html.show(node);
	/*	KHTML sucks here: it is unable to wipe in the SWF. Wipe out is OK.
	 *	Here we simple display it, and call the callback routine.
	 */
	if (dojo.render.html.khtml) {
		if(callback) { callback(node, anim); }
		return;
	}

	//pataki@: the original node.offsetHeight didn't work with Opera
	var height = savedHeight.split('px')[0];
	var anim = dojo.fx.html.wipeInToHeight(node, duration, height, function(e) {
		// pataki@: This is bad for Opera, so I commented out
		//node.style.height = savedHeight || "auto";
		if(callback) { callback(node, anim); }
	}, dontPlay);
};

/*	Displays a hallatlan movie.
**		hallatlanID: the movie's ID as defined by hallatlan.hu
**		containerID: ID of the HTML in which the display should be put
**		linkID: ID of the element that triggers hallatlan display. It must be in the
**				container, which has the containerID.
**
**	This function uses AJAX to get the hallatlan display dynamically.
*/
function
wipeInHallatlan(
	hallatlanID,
	containerID,
	linkID)
{
	if (!_currentDomain) {
		var domain = document.location.toString().match( /:\/\/([^\/]*)/ );
		_currentDomain = domain[1];
	}

	// Force hiding the current movie
	var doWait = 0;
	if (activeHallatlanLink) {
		activeHallatlanLink.onclick.call();
		doWait = 200;
	}

	// Mozilla needs EMBED, while IE works with OBJECT to play SWF
   	var doParam = "object";
	if (dojo.render.html.mozilla) {
		doParam = "embed";
	}

	dojo.io.bind({
	    url: "http://"+_currentDomain+"/hallatlan.hu/get_hallatlan.php?action=getHtml&id="+hallatlanID+"&do="+doParam,
	    load: function(type, data, evt) {
			var container = dojo.byId(containerID);

			// dojo.html.createNodesFromText and dojo.dom.insertAfter
			// didn't work with Flash in IE, so we fall back to innerHTML hacking
			container.innerHTML += data;

			var hallatlan = dojo.byId('hallatlan');
			hallatlan.style.display = "none";

			var hallatlanCaption = dojo.byId('hallatlan_caption');
			hallatlanCaption.style.display = "none";

			/*	In case of a paralell wipe out this is run asynchronously
			 */
			setTimeout(function(){
							wipeInSWF(hallatlan, 300, function(){
								// show the caption once the movie is displayed
								hallatlanCaption.style.display = "block";
							});

							// Toggle the link and remember that this is the active one
							link = dojo.byId(linkID);
							activeHallatlanLink = link;
							//link.innerHTML = "<span>Csukj</span>";
							link.onclick = function(evt) {
								wipeOutHallatlan(hallatlanID, containerID, linkID);
								return false;
							}
						},
						doWait);
			return false;
	    },
	    mimetype: "text/plain"
	});
}

function
doWipeInHallatlan(
	hallatlanID,
	containerID,
	linkID)
{

}

/*
**	Removes the curently displayed hallatlan movie
**
**
*/
function
wipeOutHallatlan(
	hallatlanID,
	containerID,
	linkID)
{
	// Clear the currently active link
	activeHallatlanLink = null;

	var container = dojo.byId(containerID);
	var link = dojo.byId(linkID);
	var hallatlanContainer = dojo.byId('hallatlan_container');
	var hallatlan = dojo.byId('hallatlan');
	var hallatlanCaption = dojo.byId('hallatlan_caption');
	var wipedOut = false;

	// Avoid ID clash with parallel wipe in.
	hallatlan.id = null;
	hallatlanContainer.id = null;
	hallatlanCaption.id = null;


	dojo.graphics.htmlEffects.wipeOut(hallatlan, 300,
								function(){
									container.removeChild(hallatlanContainer);
								});

	//link.innerHTML = "<span>Nyiss</span>";
	link.onclick = function(evt) {
				wipeInHallatlan(hallatlanID, containerID, linkID);
				return false;
			}

}

/*	Somewhat intelligent text-to-speech playback.
**	Use the flash player wherever possible.
**	If no flash or wrong version fall back to mp3 download
*/
var _szotarFlashDetected = false;
var _szotarFlashOK = false;

function
playTextToSpeech (
	what, file)
{
	if (soundManager == null) {
		return true;
	}
		
	if (!_szotarFlashDetected) {
		_szotarFlashDetected = true;
		var version = deconcept.SWFObjectUtil.getPlayerVersion();
		//alert(version.major+ "."+version.major+"."+version.rev);
		if (version.major < 9) {
 	 		hasConsole = (typeof console != 'undefined' && typeof console.log != 'undefined');
 	 		if (hasConsole) {
				if (version.major == 0) {
					console['error']("Flash plugin nem található. Flash plugin not detected.");
				}
				else {
					console['error']("Flash version detected: "+version.major+ "."+version.major+"."+version.rev);
				}
				console['error']("A SZTAKI hangos szótár 9-es vagy újabb flashel müxik. Flash version 9 or greater is required for SZTAKI Talking Dictionary."); 
			}
			_szotarFlashOK = false;			
		}
		else {
			_szotarFlashOK = true;
		}
	}	
	
	if (_szotarFlashOK) {
		soundManager.stopAll();
		soundManager.play(what, file);
		return false;
	}
	
	return true;
}


//<!-- http://www.mozilla.org/docs/web-developer/sniffer/browser_type.html
// Ultimate client-side JavaScript client sniff. Version 3.03
// (C) Netscape Communications 1999-2001.  Permission granted to reuse and distribute.
// Revised 17 May 99 to add is_nav5up and is_ie5up (see below).
// Revised 20 Dec 00 to add is_gecko and change is_nav5up to is_nav6up
//                      also added support for IE5.5 Opera4&5 HotJava3 AOLTV
// Revised 22 Feb 01 to correct Javascript Detection for IE 5.x, Opera 4,
//                      correct Opera 5 detection
//                      add support for winME and win2k
//                      synch with browser-type-oo.js
// Revised 26 Mar 01 to correct Opera detection
// Revised 02 Oct 01 to add IE6 detection

// Everything you always wanted to know about your JavaScript client
// but were afraid to ask. Creates "is_" variables indicating:
// (1) browser vendor:
//     is_nav, is_ie, is_opera, is_hotjava, is_webtv, is_TVNavigator, is_AOLTV
// (2) browser version number:
//     is_major (integer indicating major version number: 2, 3, 4 ...)
//     is_minor (float   indicating full  version number: 2.02, 3.01, 4.04 ...)
// (3) browser vendor AND major version number
//     is_nav2, is_nav3, is_nav4, is_nav4up, is_nav6, is_nav6up, is_gecko, is_ie3,
//     is_ie4, is_ie4up, is_ie5, is_ie5up, is_ie5_5, is_ie5_5up, is_ie6, is_ie6up, is_hotjava3, is_hotjava3up,
//     is_opera2, is_opera3, is_opera4, is_opera5, is_opera5up
// (4) JavaScript version number:
//     is_js (float indicating full JavaScript version number: 1, 1.1, 1.2 ...)
// (5) OS platform and version:
//     is_win, is_win16, is_win32, is_win31, is_win95, is_winnt, is_win98, is_winme, is_win2k
//     is_os2
//     is_mac, is_mac68k, is_macppc
//     is_unix
//     is_sun, is_sun4, is_sun5, is_suni86
//     is_irix, is_irix5, is_irix6
//     is_hpux, is_hpux9, is_hpux10
//     is_aix, is_aix1, is_aix2, is_aix3, is_aix4
//     is_linux, is_sco, is_unixware, is_mpras, is_reliant
//     is_dec, is_sinix, is_freebsd, is_bsd
//     is_vms
//
// See http://www.it97.de/JavaScript/JS_tutorial/bstat/navobj.html and
// http://www.it97.de/JavaScript/JS_tutorial/bstat/Browseraol.html
// for detailed lists of userAgent strings.
//
// Note: you don't want your Nav4 or IE4 code to "turn off" or
// stop working when new versions of browsers are released, so
// in conditional code forks, use is_ie5up ("IE 5.0 or greater")
// is_opera5up ("Opera 5.0 or greater") instead of is_ie5 or is_opera5
// to check version in code which you want to work on future
// versions.

    // convert all characters to lowercase to simplify testing
    var agt=navigator.userAgent.toLowerCase();

    // *** BROWSER VERSION ***
    // Note: On IE5, these return 4, so use is_ie5up to detect IE5.
    var is_major = parseInt(navigator.appVersion);
    var is_minor = parseFloat(navigator.appVersion);

    // Note: Opera and WebTV spoof Navigator.  We do strict client detection.
    // If you want to allow spoofing, take out the tests for opera and webtv.
    var is_nav  = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
                && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
                && (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1));
    var is_nav2 = (is_nav && (is_major == 2));
    var is_nav3 = (is_nav && (is_major == 3));
    var is_nav4 = (is_nav && (is_major == 4));
    var is_nav4up = (is_nav && (is_major >= 4));
    var is_navonly      = (is_nav && ((agt.indexOf(";nav") != -1) ||
                          (agt.indexOf("; nav") != -1)) );
    var is_nav6 = (is_nav && (is_major == 5));
    var is_nav6up = (is_nav && (is_major >= 5));
    var is_gecko = (agt.indexOf('gecko') != -1);


    var is_ie     = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
    var is_ie3    = (is_ie && (is_major < 4));
    var is_ie4    = (is_ie && (is_major == 4) && (agt.indexOf("msie 4")!=-1) );
    var is_ie4up  = (is_ie && (is_major >= 4));
    var is_ie5    = (is_ie && (is_major == 4) && (agt.indexOf("msie 5.0")!=-1) );
    var is_ie5_5  = (is_ie && (is_major == 4) && (agt.indexOf("msie 5.5") !=-1));
    var is_ie5up  = (is_ie && !is_ie3 && !is_ie4);
    var is_ie5_5up =(is_ie && !is_ie3 && !is_ie4 && !is_ie5);
    var is_ie6    = (is_ie && (is_major == 4) && (agt.indexOf("msie 6.")!=-1) );
    var is_ie6up  = (is_ie && !is_ie3 && !is_ie4 && !is_ie5 && !is_ie5_5);

    // KNOWN BUG: On AOL4, returns false if IE3 is embedded browser
    // or if this is the first browser window opened.  Thus the
    // variables is_aol, is_aol3, and is_aol4 aren't 100% reliable.
    var is_aol   = (agt.indexOf("aol") != -1);
    var is_aol3  = (is_aol && is_ie3);
    var is_aol4  = (is_aol && is_ie4);
    var is_aol5  = (agt.indexOf("aol 5") != -1);
    var is_aol6  = (agt.indexOf("aol 6") != -1);

    var is_opera = (agt.indexOf("opera") != -1);
    var is_opera2 = (agt.indexOf("opera 2") != -1 || agt.indexOf("opera/2") != -1);
    var is_opera3 = (agt.indexOf("opera 3") != -1 || agt.indexOf("opera/3") != -1);
    var is_opera4 = (agt.indexOf("opera 4") != -1 || agt.indexOf("opera/4") != -1);
    var is_opera5 = (agt.indexOf("opera 5") != -1 || agt.indexOf("opera/5") != -1);
    var is_opera5up = (is_opera && !is_opera2 && !is_opera3 && !is_opera4);

    var is_webtv = (agt.indexOf("webtv") != -1);

    var is_TVNavigator = ((agt.indexOf("navio") != -1) || (agt.indexOf("navio_aoltv") != -1));
    var is_AOLTV = is_TVNavigator;

    var is_hotjava = (agt.indexOf("hotjava") != -1);
    var is_hotjava3 = (is_hotjava && (is_major == 3));
    var is_hotjava3up = (is_hotjava && (is_major >= 3));

    // *** JAVASCRIPT VERSION CHECK ***
    var is_js;
    if (is_nav2 || is_ie3) is_js = 1.0;
    else if (is_nav3) is_js = 1.1;
    else if (is_opera5up) is_js = 1.3;
    else if (is_opera) is_js = 1.1;
    else if ((is_nav4 && (is_minor <= 4.05)) || is_ie4) is_js = 1.2;
    else if ((is_nav4 && (is_minor > 4.05)) || is_ie5) is_js = 1.3;
    else if (is_hotjava3up) is_js = 1.4;
    else if (is_nav6 || is_gecko) is_js = 1.5;
    // NOTE: In the future, update this code when newer versions of JS
    // are released. For now, we try to provide some upward compatibility
    // so that future versions of Nav and IE will show they are at
    // *least* JS 1.x capable. Always check for JS version compatibility
    // with > or >=.
    else if (is_nav6up) is_js = 1.5;
    // NOTE: ie5up on mac is 1.4
    else if (is_ie5up) is_js = 1.3

    // HACK: no idea for other browsers; always check for JS version with > or >=
    else is_js = 0.0;

    // *** PLATFORM ***
    var is_win   = ( (agt.indexOf("win")!=-1) || (agt.indexOf("16bit")!=-1) );
    // NOTE: On Opera 3.0, the userAgent string includes "Windows 95/NT4" on all
    //        Win32, so you can't distinguish between Win95 and WinNT.
    var is_win95 = ((agt.indexOf("win95")!=-1) || (agt.indexOf("windows 95")!=-1));

    // is this a 16 bit compiled version?
    var is_win16 = ((agt.indexOf("win16")!=-1) ||
               (agt.indexOf("16bit")!=-1) || (agt.indexOf("windows 3.1")!=-1) ||
               (agt.indexOf("windows 16-bit")!=-1) );

    var is_win31 = ((agt.indexOf("windows 3.1")!=-1) || (agt.indexOf("win16")!=-1) ||
                    (agt.indexOf("windows 16-bit")!=-1));

    var is_winme = ((agt.indexOf("win 9x 4.90")!=-1));
    var is_win2k = ((agt.indexOf("windows nt 5.0")!=-1));

    // NOTE: Reliable detection of Win98 may not be possible. It appears that:
    //       - On Nav 4.x and before you'll get plain "Windows" in userAgent.
    //       - On Mercury client, the 32-bit version will return "Win98", but
    //         the 16-bit version running on Win98 will still return "Win95".
    var is_win98 = ((agt.indexOf("win98")!=-1) || (agt.indexOf("windows 98")!=-1));
    var is_winnt = ((agt.indexOf("winnt")!=-1) || (agt.indexOf("windows nt")!=-1));
    var is_win32 = (is_win95 || is_winnt || is_win98 ||
                    ((is_major >= 4) && (navigator.platform == "Win32")) ||
                    (agt.indexOf("win32")!=-1) || (agt.indexOf("32bit")!=-1));

    var is_os2   = ((agt.indexOf("os/2")!=-1) ||
                    (navigator.appVersion.indexOf("OS/2")!=-1) ||
                    (agt.indexOf("ibm-webexplorer")!=-1));

    var is_mac    = (agt.indexOf("mac")!=-1);
    // hack ie5 js version for mac
    if (is_mac && is_ie5up) is_js = 1.4;
    var is_mac68k = (is_mac && ((agt.indexOf("68k")!=-1) ||
                               (agt.indexOf("68000")!=-1)));
    var is_macppc = (is_mac && ((agt.indexOf("ppc")!=-1) ||
                                (agt.indexOf("powerpc")!=-1)));

    var is_sun   = (agt.indexOf("sunos")!=-1);
    var is_sun4  = (agt.indexOf("sunos 4")!=-1);
    var is_sun5  = (agt.indexOf("sunos 5")!=-1);
    var is_suni86= (is_sun && (agt.indexOf("i86")!=-1));
    var is_irix  = (agt.indexOf("irix") !=-1);    // SGI
    var is_irix5 = (agt.indexOf("irix 5") !=-1);
    var is_irix6 = ((agt.indexOf("irix 6") !=-1) || (agt.indexOf("irix6") !=-1));
    var is_hpux  = (agt.indexOf("hp-ux")!=-1);
    var is_hpux9 = (is_hpux && (agt.indexOf("09.")!=-1));
    var is_hpux10= (is_hpux && (agt.indexOf("10.")!=-1));
    var is_aix   = (agt.indexOf("aix") !=-1);      // IBM
    var is_aix1  = (agt.indexOf("aix 1") !=-1);
    var is_aix2  = (agt.indexOf("aix 2") !=-1);
    var is_aix3  = (agt.indexOf("aix 3") !=-1);
    var is_aix4  = (agt.indexOf("aix 4") !=-1);
    var is_linux = (agt.indexOf("inux")!=-1);
    var is_sco   = (agt.indexOf("sco")!=-1) || (agt.indexOf("unix_sv")!=-1);
    var is_unixware = (agt.indexOf("unix_system_v")!=-1);
    var is_mpras    = (agt.indexOf("ncr")!=-1);
    var is_reliant  = (agt.indexOf("reliantunix")!=-1);
    var is_dec   = ((agt.indexOf("dec")!=-1) || (agt.indexOf("osf1")!=-1) ||
           (agt.indexOf("dec_alpha")!=-1) || (agt.indexOf("alphaserver")!=-1) ||
           (agt.indexOf("ultrix")!=-1) || (agt.indexOf("alphastation")!=-1));
    var is_sinix = (agt.indexOf("sinix")!=-1);
    var is_freebsd = (agt.indexOf("freebsd")!=-1);
    var is_bsd = (agt.indexOf("bsd")!=-1);
    var is_unix  = ((agt.indexOf("x11")!=-1) || is_sun || is_irix || is_hpux ||
                 is_sco ||is_unixware || is_mpras || is_reliant ||
                 is_dec || is_sinix || is_aix || is_linux || is_bsd || is_freebsd);

    var is_vms   = ((agt.indexOf("vax")!=-1) || (agt.indexOf("openvms")!=-1));

//--> end hide JavaScript



///////// Origo webaudit support

WEBAUDIT=function() {
    
  this.WACID=null;
  this.WACIDName="WACID";
  
  
  this.getCookie=function(name)  {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++)
    {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
  }
  
  this.setCookie=function(name,value,topDomain) {
    var date = new Date(2020,12,31,23,59,59);
    var expires = "; expires="+date.toGMTString();
    document.cookie = name+"="+value+expires+"; path=/; domain=" + topDomain;  
  }
  
  this.generateID=function(splitter) {
    var sp=(splitter) ? splitter : 'A';
    var now=new Date();
    return Date.parse(now.toGMTString()) + sp + Math.floor(Math.random()*1000000);
  }
  
  this.getTopDomain=function(fullDomain) {
    var darabok=fullDomain.split('.');
    return darabok[(darabok.length-2)] + '.' + darabok[(darabok.length-1)];
  }
  
  this.getDomain=function(url) {
    var urlDarabok=url.split('/');
    return urlDarabok[2];
  }
  
  this.WACID=this.getCookie(this.WACIDName);
}

var wa=new WEBAUDIT();
var felbontas = "";
var same =  Math.floor(Math.random()*1000000);

if(wa.WACID==null)
{
  wa.WACID=wa.generateID('A');
  wa.setCookie(wa.WACIDName,wa.WACID,wa.getTopDomain(wa.getDomain(document.URL)));
}

same = same + "@welid=" + wa.WACID;
if(screen) felbontas='@felbontas='+screen.width+'x'+screen.height;
same = same + felbontas;


////////////////////////////
//
// Virtual keyboard support
//
//////////////////////////


var isIE6 = function()
{
	
	var 
	ua=navigator.userAgent.toLowerCase(),
	is=function(t){ return ua.indexOf(t) != -1; },
	h=document.getElementsByTagName('html')[0],
	b=(!(/opera|webtv/i.test(ua))&&/msie (\d)/.test(ua))?('ie ie'+RegExp.$1):is('gecko/')? 'gecko':is('opera/9')?'opera opera9':/opera (\d)/.test(ua)?'opera opera'+RegExp.$1:is('konqueror')?'konqueror':is('applewebkit/')?'webkit safari':is('mozilla/')?'gecko':'';
	
	if ( b == 'ie ie6' )
	{
		
		return true;
		
	}
	else
	{
		
		return false;
		
	}
	
}

/* html specific parameters */

// language
var sLanguage = "HUN"; // HUN / GER / FRA / ITA / POL //

// the id of the text input element
var sTextboxId = 'searchBox';

// the id of container div
var sKeyboardId = 'virtualKeyboard';

// the id of the button that is used to show the virtual keyboard
var sToggleButtonId = 'searchButton';

// the id of the select box, because of an IE6 hack
//var sHideSelectboxIE = 'findSelect';
var sSelectboxId = 'findSelect';

// checking if the current browser is IE6	
var isIExplorer6 = isIE6();
	
// textbox handler
var oTextboxHandler;

// virtual keyboard
var oVirtualKeyboard

var bVirtualKeyboardOn = false;

function toggleVirtualKeyboard(){
	if(bVirtualKeyboardOn)
		hideVirtualKeyboard();
	else
		showVirtualKeyboard();
}

function hideVirtualKeyboard()
{
/*	
	if ( isIE6() )
	{
		document.getElementById( sSelectboxId ).style.visibility = "visible";
		
		
		// IE6 HACK
		// hiding the image of the seletbox so that the real selectbox appears
		
		document.getElementById( sHideSelectboxIE ).style.display = "block";
		
		var oSelectboxImage = document.getElementById( "selectBoxImg" );
		oSelectboxImage.style.display = "none";
		
	}
*/

	$("#" + sKeyboardId).hide("fast");
	bVirtualKeyboardOn = false;
	document.getElementById("vkImgHidden").style.display = "block";
	document.getElementById("vkImgVisible").style.display = "none";
	document.getElementById("vk").value = "0"
	
}

function showVirtualKeyboard()
{
/*
	if ( isIE6() )
	{
		
		document.getElementById( sSelectboxId ).style.visibility = "hidden";
		// IE6 HACK
		// loading an image of a selectbox instead of the selectbox, 
		// so that the menu will appear on top of the selectbox (or at least its image) 
		
		document.getElementById( sHideSelectboxIE ).style.display = "none";
		
		var oSelectboxImage = document.getElementById( "selectBoxImg" );
		oSelectboxImage.style.marginBottom = "5px";
		oSelectboxImage.style.display = "block";
	}
*/
	
	$( "#" + sKeyboardId ).show("fast");
	bVirtualKeyboardOn = true;
	document.getElementById("vkImgHidden").style.display = "none";
	document.getElementById("vkImgVisible").style.display = "block";
	document.getElementById("vk").value = "1";
}


// Called when page is loaded
var initVirtualKeyboard = function(lang, vkState)
{
	sLanguage = lang;
	
	// Show or not keyboard by default
	if (vkState == 1) {
		//$( "#" + sToggleButtonId ).toggle(hideVirtualKeyboard, showVirtualKeyboard);	
		$( "#" + sToggleButtonId ).toggle(toggleVirtualKeyboard, toggleVirtualKeyboard);
		showVirtualKeyboard();
	}
	else {
		// set toggle function for the button	
		//$( "#" + sToggleButtonId ).toggle(showVirtualKeyboard, hideVirtualKeyboard);
		$( "#" + sToggleButtonId ).toggle(toggleVirtualKeyboard, toggleVirtualKeyboard);
	}


	// new textbox handler	
	oTextboxHandler = new TextboxHandler( sTextboxId );

	// new virtual keyboard
	oVirtualKeyboard = new VirtualKeyboard(sLanguage, sTextboxId, sKeyboardId);
	
	// setting textbox handler of the virtual keyboard
	oVirtualKeyboard.setTextboxHandler( oTextboxHandler );

	// add close button to top right corner of virtual keyboard
	addCloseButtonToVirutalKeyboard();

	// creating virtual keyboard	
	oVirtualKeyboard.createKeyboard( sLanguage );	

	// these event handlers are necessary to ensure that caret information is not lost even after a textbox loses focus.
	// the event handlers trigger the saving of the carret on the following events.
	document.getElementById(sTextboxId).onclick = function()
	{
		oTextboxHandler.getCarPos();	
	}
	document.getElementById(sTextboxId).onchange = function()
	{
		oTextboxHandler.getCarPos();	
	}
	document.getElementById(sTextboxId).onkeyup = function()
	{
		oTextboxHandler.getCarPos();	
	}
	document.getElementById(sTextboxId).onmouseup = function()
	{
		oTextboxHandler.getCarPos();	
	}
	
 };

function addCloseButtonToVirutalKeyboard(){
	var closeButton = document.getElementById("imgClose");
	var realButton = document.createElement('img');
	realButton.src = closeButton.src;
	realButton.id = "vkCloseButton";
	realButton.onclick = function(){hideVirtualKeyboard()};
	document.getElementById(sKeyboardId).appendChild(realButton);
}

function changeVirtualKeyboard(newLang)
{
	oVirtualKeyboard.removeKeyboard();
	addCloseButtonToVirutalKeyboard();
	oVirtualKeyboard.createKeyboard(newLang);


	/* test code - placed here temporarily
	var myButton = document.createTextNode('x');
	var myDiv = document.createElement('div');
	myDiv.id = "closeVk"
	myDiv.appendChild(myButton);
	myDiv.onclick = function(){hideVirtualKeyboard()};
	document.getElementById(sKeyboardId).appendChild(myDiv);
	*/
}

function hideVirtualKeyboardAndFocusWord()
{
	if (bVirtualKeyboardOn) {
		hideVirtualKeyboard();
		selectWordInField();
	}
}

function bindExternalClickForVirtualKeyboard()
{
	$("body").bind("click", hideVirtualKeyboardAndFocusWord);
}

function unbindExternalClickForVirtualKeyboard()
{
	$("body").unbind("click", hideVirtualKeyboardAndFocusWord);
}

