/**
    @fileoverview Globalių funkcijų ir kintamųjų failas.
*/
//---------------------------------------------------------------------
/** Parodo ar naudojamas browseris yra Internet Explorer */
var cIE = false;
/** Parodo ar naudojamas browseris yra Mozilla FireFox */
var cFF = false;
if(navigator.appName.indexOf('Netscape') != -1)cFF = true;
if(navigator.appName.indexOf('Explorer') != -1)cIE = true;
var cIE6lte = false;
if (cIE)
{
	var ra = navigator.userAgent.match(new RegExp('MSIE (\\d)', 'i'));
	if(ra!=null)
	{
		cIE6lte = ra[1] <= 6;
	}
}
var cIE7 = cIE && navigator.userAgent.indexOf('MSIE 7') != -1;
//---------------------------------------------------------------------

//DEBUG_MODE = true;

//function debug()
//{
//    if(DEBUG_MODE == true)
//        debugger;
//}

iTAB_INDEX = 100;
var objEditor2 = null;
var g_blnShowConsole = false;
var g_blnJsWindowOpened = false; // Konstanta reikalinga patikrinti ar atidarytas js langas
var g_intImageWidth = 168;
var g_intImageHeight = 224;
var g_intSmallImageWidth = 42;
var g_intSmallImageHeight = 56;

var cDecimalSymbol = ',';
var cFloatPrecision = 2;
var cGroupingSymbol = '.';
/**
    Skaičiaus grupavimo būdas.
    0 - negrupuoti;
    1 - grupuoti tūkstančiais;
    2 - pirma grupė tūkstančiais, o po to šimtais.
*/
var cDigitGroupingType = 0; 
var cDisplayLeadingZero = 1; // true/false
var cDisplayTrailingZero = 0; // true/false

var cDoublePrecision = 3;

var cShortDateFormat = 'yyyy.MM.dd';
var cLongDateFormat = 'yyyy \'m.\' MMMM d \'d.\'';
var cTimeFormat = 'HH:mm:ss';
var cYearAhead = 22;

var intLastNr = 0;
/**
    Generuoja autoincrementinį Id.
*/
function g_str_fIdGenerator()
{
    intLastNr++;
    return 'gen' + intLastNr;
}

/**
    @name Array
    @class Masyvo klasė papildyta keliomis reikalingomis funkcijomis.
*/
/**
    @name String
    @class Eilutės klasė papildyta keliomis reikalingomis funkcijomis.
*/
/**
    @name Function
    @class Funkcijos klasė papildyta keliomis reikalingomis funkcijomis.
*/
/**
    @name XMLDocument
    @class XMLDocument klasė papildyta keliomis reikalingomis funkcijomis.
*/
/**
    @name Element
    @class Element klasė papildyta keliomis reikalingomis funkcijomis.
*/
//<><><>////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////                                                 ///////////////
////////////////                   DOM funkcijos                 ///////////////
////////////////                                                 ///////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

/**
    Jei paduodamas stringas, tai pagal jį ieško elemento, jei paduodamas DOMElementas, tai jį ir grąžina.
    Prideda kodui lankstumo.
    @param p_objArbitraryObject {DOMElement/String} DOMElementas, arba ID.
*/
function g_obj_fElement(p_objArbitraryObject)
{ 
    if (typeof(p_objArbitraryObject) == 'string')
    {
        return document.getElementById(p_objArbitraryObject); 
    }
    return p_objArbitraryObject;
}

/**
    Nustato elemento vidinį tekstą.
    @param p_objElement {DOMElement/String} DOMElementas, arba ID.
    @param p_strText Tekstas, kurį reikia pasetinti.
*/
function g_fSetInnerText(p_objElement, p_strText)
{ 
    p_objElement = g_obj_fElement(p_objElement);
    if (!p_objElement)
        return;
    if (cIE)    
    {
        p_objElement.innerText = p_strText;
    }
    else 
    {
        p_objElement.textContent = p_strText;
    }
}

/**
    Prideda elemento vidinį tekstą prie jau egzistuojančio.
    @param p_objArbitraryObject {DOMElement/String} DOMElementas, arba ID.
    @param p_strText Tekstas, kurį reikia pridėti.
*/
function g_fAddInnerText(p_objElement, p_strText)
{ 
    p_objElement = g_obj_fElement(p_objElement);
    if (!p_objElement)
        return;
    if (p_objElement.innerText)    
    {
        p_objElement.innerText += p_strText;
    }
    else
    {
        p_objElement.textContent += p_strText;
    }
}

function bln_fIsImageOk(p_objImage)
{
    // During the onload event, IE correctly identifies any images
    // that weren't downloaded as not complete. Others should too.
    // Gecko-based browsers act like NS4 in that they report this
    // incorrectly: they always return true.
    if (!p_objImage.complete) 
    {
        return false;
    }
    // However, they do have two very useful properties: naturalWidth
    // and naturalHeight. These give the true size of the image. If
    // it failed to load, either of these should be zero.
    if (typeof p_objImage.naturalWidth != "undefined" && p_objImage.naturalWidth == 0) 
    {
        return false;
    }
    // No other way of checking: assume it's ok.
    return true;
}


/*
    Paselektina visus elementus, kurie turi nurodytą klasę. Pažymimi tik p_objParent 
    tiesioginiai ar netiesioginiai vaikai turintys pavadimą p_strTagName.
*/
function g_arr_obj_fGetElementsByClassName(p_objParent, p_strTagName, p_strClassName)
{
	var arrElements = p_objParent.getElementsByTagName(p_strTagName);
	var arrReturnElements = new Array();
	var strClassName = p_strClassName.replace(/-/g, "\-");
	var objRegExp = new RegExp("(^|\s)" + strClassName + "(\s|$)");
	var objElement;
	for(var i=0, intLength = arrElements.length; i < intLength; i++){
		objElement = arrElements[i];
		if(objRegExp.test(objElement.className)){
			arrReturnElements.push(objElement);
		}
	}
	return (arrReturnElements)
}

/**
    Tas funkcijas, kurios skirtingose naršyklėse labai skiriasi kursim tokiu būdu. Tam kad if būtų vykdomas tik vieną kartą.
    
if (cIE)
{
    var f1 = function(...)
    {...}
}
if (cFF)
{
    var f1 = function(...)
    {...}
}
*/


/**
    Funkcija, nuimanti tolesnį ivykio vykdymą.
    @param e {Event} Įvykis, kurį reikia stabdyti.
    @param p_blnAllowPropagation {bool} Ar leisti įvykiui toliau plisti.
    @param p_blnAllowDefault {bool} Ar leisti įvykdyti standartinę naršyklės funkciją.
    @author KM 
    @version 2 2006-10-17  
*/
if (cFF)    // FF
{
    g_fStopEvent = function(e, p_blnAllowPropagation, p_blnAllowDefault)
    {
        if (!p_blnAllowPropagation) // Jei neleidžiame toliau plisti
        {
            e.stopPropagation();
        }
        if (!p_blnAllowDefault)     // Jei neleidžiame įvykdyti standartinės naršyklės funkcijos 
        {
            e.preventDefault();
        }        
    }
}
else        // IE ir kiti browseriai
{
    g_fStopEvent = function(e, p_blnAllowPropagation, p_blnAllowDefault)
    {
        if (!p_blnAllowPropagation) // Jei neleidžiame toliau plisti
        {
            e.cancelBubble = true;
        }
        if (!p_blnAllowDefault)     // Jei neleidžiame įvykdyti standartinės naršyklės funkcijos 
        {
            if (e.keyCode != 17 && e.keyCode != 16) // jei paspausta ne shift ir ne ctrl (ju kodu keisti negalima)
            {
             // RG 2006.11.02  //VG 2008.04.04 uzkomentavau
              //  e.keyCode = 0 - e.keyCode;      // Tai pakeiciamas paspaudimo kodas
            }
            e.returnValue = false;	
        }        
    }    
}

/**
    Randa įvykį sukėlusį elementą.
    @param e Javascriptinis įvykis.
    @returns Įvykį sukėlusį elementą
    @type HTMLElement
*/
if (cIE)
{
    var getSrcElement = function (e)
    {
        return e.srcElement;    
    }    
}
if (cFF)
{
    var getSrcElement = function (e)
    {
        return e.target;    
    }
}

/**
    Gauna elementą, į kurį naviguoja įvykis.
*/
if (cIE)
{
    var g_obj_fGetNavigatingToElement = function (e)
    {
        return e.toElement;    
    }
}	
if (cFF)
{
    var g_obj_fGetNavigatingToElement = function (e)
    {
        return e.relatedTarget;   
    }    
}

/**
    Gauna elementą, iš kurio naviguoja įvykis
*/
if (cIE)
{
    var g_obj_fGetNavigatingFromElement = function (e)
    {
        return e.fromElement;    
    }
}	
if (cFF)
{
    var g_obj_fGetNavigatingFromElement = function (e)
    {
        return e.currentTarget;    
    }    
}


//function getSelectionStart(input) {
//	if (is_gecko)
//		return input.selectionStart;
//	var range = document.selection.createRange();
//	var isCollapsed = range.compareEndPoints("StartToEnd", range) == 0;
//	if (!isCollapsed)
//		range.collapse(true);
//	var b = range.getBookmark();
//	return b.charCodeAt(2) - 2;
//};

//function getSelectionEnd(input) {
//	if (is_gecko)
//		return input.selectionEnd;
//	var range = document.selection.createRange();
//	var isCollapsed = range.compareEndPoints("StartToEnd", range) == 0;
//	if (!isCollapsed)
//		range.collapse(false);
//	var b = range.getBookmark();
//	return b.charCodeAt(2) - 2;
//};

/**
    Gauna informacija apie kursoriaus vietą inpute.
    @returns Objektą, kuris turi pradinę ir galinę kursoriaus vietas.
        {
            selectionStart: pažymėjimo pradžia
            selectionEnd: pažymėjimo pabaiga
            selectedText: pažymėtas tekstas
        }
*/
if (cIE)
{
    g_hsh_fGetCursorInformation = function (p_objInput)
    {
        var intSelectionStart = 0;
        var intSelectionEnd = 0;
        var strSelectedText = '';
        
        var strOldValue = p_objInput.value;
        var strSpecialSymbol = '~@#@~';
        var selectionRange = document.selection.createRange();	  
        
        // randamas paselectintas textas   
        var oldSelection = selectionRange.text;            // paselectintas textas
        strSelectedText = selectionRange.text;
        
        // pakeiciamas selectionas ir randama caret'o pozicija
        selectionRange.text = strSpecialSymbol;
        
        // randama caret'o pozicija
        var strNewValue = p_objInput.value;
        intSelectionStart = strNewValue.indexOf(strSpecialSymbol);
        intSelectionEnd = intSelectionStart + oldSelection.length;
     
        // istrinamas spec simbolis    
        var selectionRangeEnd = document.selection.createRange();	 // paselectinamas spec simbolis
        var a = selectionRangeEnd.compareEndPoints('StartToStart', selectionRange);
        var b = selectionRangeEnd.compareEndPoints('StartToEnd', selectionRange);
        var c = selectionRangeEnd.compareEndPoints('EndToEnd', selectionRange);
        var d = selectionRangeEnd.compareEndPoints('EndToStart', selectionRange);
        
        if(c != -1 && d != -1)
        {
            selectionRange.move('character', -5);    // jei antra karta 
        }
        selectionRangeEnd.setEndPoint('StartToStart', selectionRange);
        selectionRangeEnd.select();
        document.selection.clear();
        
        // atstatomas selectionas
        var selectionRangeStart = document.selection.createRange();	
        selectionRange.text = oldSelection;
        selectionRange.move('character', oldSelection.length);
        var selectionRangeEnd = document.selection.createRange();	
        selectionRangeEnd.setEndPoint('StartToStart', selectionRangeStart);
        selectionRangeEnd.select();
	    
        return {
            selectionStart: intSelectionStart, 
            selectionEnd: intSelectionEnd, 
            selectedText: strSelectedText};
    }
}
if (cFF)
{
    g_hsh_fGetCursorInformation = function (p_objInput)
    {
        var strSelectedText = p_objInput.value.substring(p_objInput.selectionStart, p_objInput.selectionEnd);
		var intSelectionStart = p_objInput.selectionStart;
        var intSelectionEnd = p_objInput.selectionEnd;
        return {
            selectionStart: intSelectionStart, 
            selectionEnd: intSelectionEnd, 
            selectedText: strSelectedText};
    }
}   

/**
    Gauna paspaustos raidės kodą.
*/
if (cIE)
{
    g_int_fGetCharCode = function(p_objEvent)
    {
        return p_objEvent.keyCode;
    }   
}
if (cFF)
{
    g_int_fGetCharCode = function(p_objEvent)
    {
        return p_objEvent.charCode;   
    }    
}

/**
    Gauna paspausto mygtuko kodą.
*/
if (cIE)
{
    g_int_fGetKeyCode = function(p_objEvent)
    {
        return p_objEvent.keyCode;
    }   
}
if (cFF)
{
    g_int_fGetKeyCode = function(p_objEvent)
    {
        return p_objEvent.which;   
    }    
}

/**
    Gauna įrašomą simbolį.
*/
if (cIE)
{
    g_str_fGetInputChar = function(p_objEvent)
    {
        return String.fromCharCode(p_objEvent.keyCode);
    }   
}
if (cFF)
{
    g_str_fGetInputChar = function(p_objEvent)
    {
        return String.fromCharCode(p_objEvent.which);   
    }    
}

/**
    Pažymi inputo elementą nuo starto iki galo indeksų
*/
if (cIE)
{
    g_fSetSelectionRange = function(p_objInput, p_intStart, p_intEnd)
    {
        var strValue = p_objInput.value;
        var strEnding = strValue.substr(0, p_intEnd);
        var strBegining = strValue.substr(0, p_intStart).replace(/\r\n/g, '\n');
        var strEnding = strValue.substr(0, p_intEnd).replace(/\r\n/g, '\n');
        strValue = strValue.replace(/\r\n/g, '\n');
        var objRange = p_objInput.createTextRange();
        objRange.moveStart('character', strBegining.length);
        objRange.moveEnd('character', strEnding.length - strValue.length);
        objRange.select();
    }
}
if (cFF)
{
    g_fSetSelectionRange = function (p_objInput, p_intStart, p_intEnd)
    {
        p_objInput.focus();
        p_objInput.setSelectionRange(p_intStart, p_intEnd);
    }
}

/**
    KM 2006-07-18
    Funkcija, panaikinanti stiliaus taisyklę iš visu užloadintu css dokumentų
    Stiliaus selectoriai gali buti su ',' (kableliu), pvz.: 'TR.rowSelected TD, .gridHeaderOver DIV',
    bet skirtingi, browseriai jį interpretuoja skirtingai:
    FF - nuima stiliu, pagal tiksliai sutampanti selectorių, t.y. jei bus stiliai 
      'TR.rowSelected TD, .gridHeaderOver DIV' ir 'TR.rowSelected TD', ir bus pasirinkta nuimti 
      'TR.rowSelected TD, .gridHeaderOver DIV' stiliu, tai jis pirmą stiliu nuims, o antrą paliks.
      Jei bus užduota nuimti stilių 'TR.rowSelected TD', tai antrasis bus nuimtas, o pirmasis paliktas.
    IE - stilius išskaido pagal ',' ženklą, todėl, jei nurodoma nuimti 'TR.rowSelected TD, .gridHeaderOver DIV',
      tai funkcija skaidys selectorių i du ir atskirai nuims. Tokiu atveju bus nuimti abu stiliai. 
    @param p_strSelector - stiliaus selectorius.  
*/     
function g_fRemoveStyle(p_strSelector)
{
    p_strSelector = p_strSelector.toLowerCase();      
    if (cIE)
    {
        var arr_strSelectorTokens = p_strSelector.split(',');
        if (arr_strSelectorTokens.length > 1)                   //jei buvo rastas kablelis
        {
            for (var k = 0; k < arr_strSelectorTokens.length; k++)
            {
                g_fRemoveStyle(arr_strSelectorTokens[k]);       //tada ?od?iai apdorojami atskirai
            }   
            return; // I?einam, nes stiliai bus prie? tai i?valyti 
        }
    }
    
    var sheetList = document.styleSheets;
    var ruleList;
    var i, j;    
    //  Pereinam per stilių failus atvirkščia tvarka, nei buvo importuoti
    for (i = sheetList.length-1; i >= 0; i--)
    {
        if (cIE)
            ruleList = sheetList[i].rules;
        if (cFF)
            ruleList = sheetList[i].cssRules;
        
        for (j=0; j<ruleList.length; j++)           // Pereinam per visas taisykles
        {
            if (((cFF && ruleList[j].type == CSSRule.STYLE_RULE) || (cIE)) && 
               ruleList[j].selectorText.toLowerCase() == p_strSelector) // jei stiliaus selectoriai sutampa
            {
                //consoleA('I?metam stiliu');
                if (sheetList[i].removeRule)            // IE   
                    sheetList[i].removeRule(j);
                else if (sheetList[i].deleteRule)       // FF
                    sheetList[i].deleteRule(j);
                j--;
            }   
        }
    }
}
//--------------------------------------------------------------------------------------

/**
    KM 2006-07-19
    Funkcija, pridedanti stiliaus taisyklę prie pirmo užloadinto stiliaus failo (Tačiau į failą neišsisaugo)
    @p_strSelector - stiliaus selectorius.
    @p_strStyle - CSS stilius.
*/
function g_fAddStyle(p_strSelector, p_strStyle)
{
    var sheetList = document.styleSheets;
    var ruleList;
    var index;    
    var sheetIndex = sheetList.length - 1;
    // Jei faile nebuvo nei vieno css failo, tai negalima pridėti stiliaus
    if (sheetList.length == 0)
        return;
        
    if (cIE)
        ruleList = sheetList[sheetIndex].rules;
    if (cFF)
        ruleList = sheetList[sheetIndex].cssRules;
    
    index = ruleList.length;
    if (index < 0) 
        index = 0;
     
    if (cFF)  
    {
        sheetList[sheetIndex].insertRule(p_strSelector + '{' + p_strStyle + '}', index);
    }  
    if (cIE)  
    {
        sheetList[sheetIndex].addRule(p_strSelector, p_strStyle, index);
    }
}

/**
    Gauna tekstą iš clipboardo.
    @type string
*/
if (cIE)
{
    var g_str_fGetClipboardText = function()
    {
        var strText = 'cEMPTY';
	    //if(window.clipboardData)
	    var strText = window.clipboardData.getData('Text');
	    return(strText);
    }   
}
if (cFF)
{
    var g_str_fGetClipboardText = function()
    {
        var strText = 'cEMPTY';
        //if(window.netscape)
		netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
		var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
		if (!clip) 
		    return strText;
		var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
		if (!trans) 
		    return strText;
		trans.addDataFlavor('text/unicode'); 	
		//trans.addDataFlavor('text/plain'); 
		clip.getData(trans, clip.kGlobalClipboard);
		var str = new Object();
		var strLength = new Object();
		try
		{
		    trans.getTransferData('text/unicode', str, strLength);
		    if (str) str = str.value.QueryInterface(Components.interfaces.nsISupportsString);
		    if (str) strText = str.data.substring(0, strLength.value / 2); 
		}
		catch(ex)
		{
		    //strText = 'cEMPTY';
		}    
	    return(strText);  
    }    
}

/**
    Kopijuoja tekstą į clipboard
    @param p_strText Kopijuojamas tekstas
*/
if (cIE)
{
    var fCopyToClipboard = function(p_text)
    {
        if(window.clipboardData || clipboardData)
        window.clipboardData.setData("Text", p_text);
        return;
    }   
}
if (cFF)
{
    var fCopyToClipboard = function(p_text)
    {
        netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
        var gClipboardHelper = Components.classes["@mozilla.org/widget/clipboardhelper;1"].
                                getService(Components.interfaces.nsIClipboardHelper);
        gClipboardHelper.copyString(p_text);
        return;
    }
}

/**
    Taip pat kopijuoja tekstą į clipboard, bet sudėtingiau.
    @param p_strText
*/
if (cIE)
{
    var bln_fCopyToClipboard = function(p_text)
    {
        if(window.clipboardData || clipboardData)
        window.clipboardData.setData("Text", p_text);
        return true;
    }   
}
if (cFF)
{
    var bln_fCopyToClipboard = function(p_text)
    {
        netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
        var copytext = p_strText;
        var str   = Components.classes["@mozilla.org/supports-string;1"].
                    createInstance(Components.interfaces.nsISupportsString);
        if (!str) 
            return false;
        str.data  = copytext;
        var trans = Components.classes["@mozilla.org/widget/transferable;1"].
                    createInstance(Components.interfaces.nsITransferable);
        if (!trans) 
            return false;
        
        trans.addDataFlavor("text/unicode");
        trans.setTransferData("text/unicode", str, copytext.length * 2);
        var clipid = Components.interfaces.nsIClipboard;
        var clip   = Components.classes["@mozilla.org/widget/clipboard;1"].getService(clipid);
        if (!clip) 
            return false;
        clip.setData(trans, null, clipid.kGlobalClipboard);
        return true;
    }
}

/**
    Nustato ar buvo paspaustas kairysis pelės mygtukas
    @param p_objEvent Event objektas
    @type bool
*/
function g_bln_fIsLeftClick(p_objEvent)
{
    return cIE && p_objEvent.button == 1 || cFF && p_objEvent.button == 0;  
}

/**
    Nustato ar buvo paspaustas dešinysis pelės mygtukas
    @param p_objEvent Event objektas
    @type bool
*/
function g_bln_fIsRightClick(p_objEvent)
{
    return p_objEvent.button == 2;    
}

/**
    Nustato ar buvo paspaustas vidurinysis pelės mygtukas
    @param p_objEvent Event objektas
    @type bool
*/
function g_bln_fIsMiddleClick(p_objEvent)
{
    return cIE && p_objEvent.button == 4 || cFF && p_objEvent.button == 1;       
}

/**
    Gauna visus tėvus nuo vaiko iki window objekto tokiu formatu:
        [tag_name].[class_name] #[id]
    @param p_objElement Elementas, kuriam reikia rasti tėvus.
*/
function g_arr_str_fGetParentChain(p_objElement)
{
    var arr_strResult = [];
    var objElement = p_objElement;
    while(objElement)
    {
        var strItem = objElement.tagName;
        if (objElement.className)
            strItem += '.' + objElement.className;
        if (objElement.id)
            strItem += ' #' + objElement.id;
        arr_strResult.push(strItem);
        var objParent = objElement.parentNode;
        if (objParent == objElement)
            break;
        objElement = objParent;
    }
    
    return arr_strResult;
}

/**
    Uždeda javascriptinį aktyvaus/neaktyvaus elemento stilių.
    @param p_objElement Elementas kurį reikia enablinti/disablinti.
    @param p_blnEnabled Jei true, tai reikia enablinti, jei false tai disablinti.
*/
if (cFF)    // FF
{
    g_fSetEnabled = function(p_objElement, p_blnEnabled)
    {
        if (p_blnEnabled)
        {
            p_objElement.style.cursor = 'pointer';
            p_objElement.style.MozOpacity = '1';    
        }
        else
        {
            p_objElement.style.cursor = 'default';
            p_objElement.style.MozOpacity = '0.5';    
        }
    }
}
else if (cIE)
{
    g_fSetEnabled = function(p_objElement, p_blnEnabled)
    {
        if (p_blnEnabled)
        {
            p_objElement.style.cursor = 'pointer';
            p_objElement.style.filter = '';    
        }
        else
        {
            p_objElement.style.cursor = 'default';
            p_objElement.style.filter = 'alpha (opacity=50)';    
        }
    }
}

if (cFF)    // FF
{
    g_fSetEnabledFilter = function(p_objElement, p_blnEnabled)
    {
        if (p_blnEnabled)
        {
            p_objElement.style.MozOpacity = '1';    
        }
        else
        {
            p_objElement.style.MozOpacity = '0.5';    
        }
    }
}
else if (cIE)
{
    g_fSetEnabledFilter = function(p_objElement, p_blnEnabled)
    {
        if (p_blnEnabled)
        {
            p_objElement.style.filter = '';    
        }
        else
        {
            p_objElement.style.filter = 'alpha (opacity=50)';    
        }
    }
}

/**
    Įterpia p_objNode į p_objParent nodą iš karto po p_objReferenceNode nodo.
*/
function g_fInsertAfter(p_objParent, p_objNode, p_objReferenceNode) 
{
	p_objParent.insertBefore(p_objNode, p_objReferenceNode.nextSibling);
}

/**
    Įterpia p_objNode į p_objParent nodą prieš pat p_objReferenceNode nodą.
*/
function g_fInsertBefore(p_objParent, p_objNode, p_objReferenceNode) 
{
	p_objParent.insertBefore(p_objNode, p_objReferenceNode);
}

// DOM funkcijos \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

//<><><>////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////                                                 ///////////////
////////////////            Įvykių uždėjimo funkcijos            ///////////////
////////////////                                                 ///////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

/**
    Metodas ant nurodyto elemento uždeda nurodytą eventą.
    @param p_objElement  HTML elementas ant kurio uždedamas eventas.
    @param p_strEventType  Evento pavadinimas be IE priesagos 'on'.
    @param p_fHandler  nuoroda i funkcija.
    @param p_objContext Funkcijos kvietimo kontekstas. Jei null, tai imamas defaultinis kontekstas.
*/
function addEvent(p_objElement, p_strEventType, p_fHandler, p_objContext)
{
    var fHandler = p_fHandler;  // KM 2007.08.06 Pridėtas kontekstas
    if (p_objContext != null && typeof(p_objContext) == 'object') // negalima uždėti funkcijos vykdymo ne ant objekto
    {
        fHandler = p_fHandler.closure(p_objContext);
    }
    if (p_objElement.addEventListener)
    {
        p_objElement.addEventListener(p_strEventType, fHandler, false);
        return( true );
    } 
    else 
    if (p_objElement.attachEvent)
    {
        var fRet = p_objElement.attachEvent("on" + p_strEventType, fHandler);
        return( fRet );
    } 
    else 
    {
        return( false );
    }
}

//-----------------------------------------------------------------------------

/**
    Metodas nuo nurodyto elemento nuima nurodyta eventa. Nuimant įvykį reikia 
    paduoti lygiai tokius pačius parametrus kaip ir uždedant, nes kitaip nenusiims.
    @param p_objElement  HTML elementas nuo kurio nuimamas eventas.
    @param p_strEventType  Evento pavadinimas be IE priesagos 'on'.
    @param p_fHandler  nuoroda i funkcija kuria nuimam nuo evento.
    @param p_objContext Funkcijos kvietimo kontekstas. Jei null, tai imamas defaultinis kontekstas.
*/
function removeEvent(p_objElement, p_strEventType, p_fHandler, p_objContext)
{
    if (p_objElement == null)
    {
        return;
    }
    var fHandler = p_fHandler;  // KM 2007.08.31 Pridėtas kontekstas
    if (p_objContext != null && typeof(p_objContext) == 'object') // negalima uždėti funkcijos vykdymo ne ant objekto
    {
        fHandler = p_fHandler.closure(p_objContext);
    }
    if (p_objElement.removeEventListener)
    { 
        p_objElement.removeEventListener(p_strEventType, fHandler, false);
        return true;
    } 
    else 
    if (p_objElement.detachEvent)
    {
        var fRet = p_objElement.detachEvent('on' + p_strEventType, fHandler);
        return(fRet);
    }
    else 
    {
        consoleA("Handler could not be removed");
    }
}

/**
    Sąsaja, kurią įgyvendinantis objektas turi įvykių valdymo sistemėlę.
    @param p_arr_strAllowedEvents Tam objektui galimų įvykių tipų sąrašas. 
*/
function iEventInterface(p_arr_strAllowedEvents)
{
    if (p_arr_strAllowedEvents)
    {
        this.hshAllowed = g_hsh_int_fMakeExistanceHash(p_arr_strAllowedEvents);
        this.bln_fEventAllowed = function(p_strEvent)
        {
            return this.hshAllowed[p_strEvent];
        }
    }
    else
    {
        this.bln_fEventAllowed = function()
        {
            return true;
        }    
    }
    
    /**
        Prie įvykio priregistruoja vieną funkciją.
        @param p_strEvent {string} Įvykio tipas.
        @param p_objContext {object} Kontekstas, kuriame bus iškviesta funkcija.
        @param p_fFunction {function} Registruojama funkcija.
        @param p_blnOneTimeRun {bool} Ar vykdyti tik vieną kartą.
    */
    this.g_fAddEvent = function(p_strEvent, p_objContext, p_fFunction, p_blnOneTimeRun)
	{
	    return this.fAddEvent(p_strEvent, p_objContext, p_fFunction, p_blnOneTimeRun);
    }	
    
    this.fAddEvent = function(p_strEvent, p_objContext, p_fFunction, p_blnOneTimeRun)
	{
	    if (!this.bln_fEventAllowed(p_strEvent))
	        return false;
	    if (typeof(p_fFunction) == 'function')
        {
            if(p_objContext == null)
                p_objContext = window;
            p_blnOneTimeRun = p_blnOneTimeRun ? true : false;
            Listener.add(this, p_strEvent, p_fFunction, p_objContext, p_blnOneTimeRun);
        }
        return true;
    }	
    //-----------------------------------------------------------------------
	/**
        Išregistruoja funkciją iš įvykio apdorojimo.
        @param p_strEvent {string} Įvykio tipas.
        @param p_objContext {object} Kontekstas, kuriame bus iškviesta funkcija.
        @param p_fFunction {function} Registruojama funkcija.
    */
	this.g_fRemoveEvent = function(p_strEvent, p_objContext, p_fFunction)
	{
	    if (!this.bln_fEventAllowed(p_strEvent))
	        return false;
	    if(p_objContext == null)
            p_objContext = window;
        Listener.remove(this, p_strEvent, p_fFunction, p_objContext);  
        return true; 
    }		    
    //-----------------------------------------------------------------------
	/**
	    Iškviečia nurodytą įvykį ir įvykdo visas funkcijas, kurios buvo prie jo priregistruotos.
	    @param p_strEvent {string} Įvykio tipas.
        @param p_objArg {object} Argumentų objektas, kuris bus paduotas visoms iškviečiamoms funkcijoms.
	*/
	this.fFireEvent = function(p_strEvent, p_objArg)
	{   
	    if (!this.bln_fEventAllowed(p_strEvent))
	        return false;
	    Listener.fire(this, p_strEvent, [p_objArg]);
	    return true; 
    }
    
    /**
        Iškviečia nurodytą įvykį ir įvykdo visas funkcijas, kurios buvo priregistruotos prie visų objektų,
        išskyrus nurodytąjį.
	    @param p_strEvent {string} Įvykio tipas.
        @param p_objArg {object} Argumentų objektas, kuris bus paduotas visoms iškviečiamoms funkcijoms.
        @param p_objExceptionObject {object} Objektas, kuriam kviesti funkcijų nereikia.
    */
    this.g_fFireEventExcept = function(p_strEvent, p_objArgs, p_objExceptionObject)
    {
        if (!this.bln_fEventAllowed(p_strEvent))
	        return false;
        Listener.fireConditional(this, p_strEvent, [p_objArgs], p_objExceptionObject, false);
        return true;
    }
    
    /**
        Iškviečia nurodytą įvykį ir įvykdo visas funkcijas, kurios buvo priregistruotos tik prie nurodyto 
        objekto.
	    @param p_strEvent {string} Įvykio tipas.
        @param p_objArg {object} Argumentų objektas, kuris bus paduotas visoms iškviečiamoms funkcijoms.
        @param p_objExclusiveObject {object} Objektas, kuriam reikia kviesti funkcijas.
    */
    this.g_fFireEventOnly = function(p_strEvent, p_objArgs, p_objExclusiveObject)
    {
        if (!this.bln_fEventAllowed(p_strEvent))
	        return false;
        Listener.fireConditional(this, tp_strEvent, [p_objArgs], p_objExclusiveObject, true);    
        return true;
    }
    
    /**
        Nurodo kiek handlerių (funkcijų) yra priregistruota prie nurodyto įvykio tipo.
        @param p_strEvent {string} Įvykio tipas.
    */
    this.int_fGetRegisteredHandlerCount = function(p_strEvent)
    {
        return Listener.getLength(this, p_strEvent);
    }
    
    /**
        Priregistruoja papildomus įvykių tipus.
        @param p_arr_strTypes Papildomų įvykių tipų masyvas.
    */
    this.g_fRegisterEventTypes = function(p_arr_strTypes)
    {
        if (this.hshAllowed == null)
        {
            this.hshAllowed = g_hsh_int_fMakeExistanceHash(p_arr_strTypes);
            this.bln_fEventAllowed = function(p_strEvent)
            {
                return this.hshAllowed[p_strEvent];
            }
        } 
        else
        {
            this.hshAllowed = g_hsh_int_fAppendExistanceHash(this.hshAllowed, p_arr_strTypes);
        }   
    }
}

/**
    Įvykių konstantų hashas.
    @static
*/
var cEvents = {};
    cEvents.cClick = 'onClick';
    cEvents.cDblClick = 'onDblClick';
    cEvents.cKeyDown = 'onKeyDown';
    cEvents.cKeyUp = 'onKeyUp';
    cEvents.cKeyPress = 'onKeyPress';
    cEvents.cChange = 'onChange';
    cEvents.cExpand = 'onExpand';
    cEvents.cCollapse = 'onCollapse';
    cEvents.cLoad = 'onLoad';
    cEvents.cLoadHeader = 'onLoadHeader';
    cEvents.cLoadContent = 'onLoadContent';
    cEvents.cSelect = 'onSelect';
    cEvents.cUnselect = 'onUnselect';
    cEvents.cMouseOver = 'onMouseOver';
    cEvents.cMouseOut = 'onMouseOut';
    cEvents.cDragStart = 'onDragStart';
    cEvents.cDragEnd = 'onDragEnd';
    cEvents.cDragOut = 'onDragOut';
    cEvents.cDragOver = 'onDragOver';
    cEvents.cDrag = 'onDrag';
    cEvents.cDrop = 'onDrop';
    cEvents.cDragFailed = 'onDragFailed';
    cEvents.cPropertyChanged = 'onPropertyChanged';
    cEvents.cSelectStart = 'onSelectStart';
    cEvents.cSelectMove = 'onSelectMove';
    cEvents.cSelectEnd = 'onSelectEnd';
    cEvents.cShow = 'onShow';
    cEvents.cHide = 'onHide';
    cEvents.cBeforeShow = 'onBeforeShow';
    cEvents.cBeforeHide = 'onBeforeHide';
    cEvents.cStateChange = 'onStateChanged';
    cEvents.cUp = 'onUp';
    cEvents.cDown = 'onDown';
    cEvents.cAccept = 'onAccept';
    cEvents.cDelete = 'onDelete';
    cEvents.cError = 'onError';
    cEvents.cValidationOK = 'onValidationOK';
    cEvents.cFocus = 'onFocus';
    cEvents.cBlur = 'onBlur';
    cEvents.cFileUploaded = 'onFileUpload';
    cEvents.cInvalidate = 'onInvalidate';
    cEvents.cSearch = 'onSearch';
    cEvents.cCreate = 'onCreate';
    cEvents.cEdit = 'onEdit';
    cEvents.cRefresh = 'onRefresh';

function g_hsh_int_fMakeExistanceHash(p_arr_strKeyArray)
{
    var hsh_intExistanceHash = {};
    for(var i = 0, intLength = p_arr_strKeyArray.length; i < intLength; i++)
    {
        hsh_intExistanceHash[p_arr_strKeyArray[i]] = 1;    
    }
    return hsh_intExistanceHash;
}

function g_hsh_int_fAppendExistanceHash(p_hsh_intOriginal, p_arr_strKeyArray)
{
    for(var i = 0, intLength = p_arr_strKeyArray.length; i < intLength; i++)
    {
        p_hsh_intOriginal[p_arr_strKeyArray[i]] = 1;    
    }
    return p_hsh_intOriginal;        
}

// Event listener implimentation for javascript. Works with native events as well as custom events. 
//
// Essentially, Listener hijacks a member of an object and makes it a pointer to an internal 
// Listener method. When the hijacked member is called, Listener fires any number of other methods 
// by proxy in whatever scope you specify. All arguments passed to the source 
// event are received by all listeners automatically.
// 
// This amounts to a very powerful event listener setup similar to "signals and slots", but without 
// the confusing nomenclature and lack of distinction between methods and events.
//
//
// syntax:
//
// Listener.add(objSource, strEventName, fpListener, objScope, blnRunOnce);
//   objSource    : the object whose events you are listening for
//   strEventName : the name of the event to listen for ("onclick", "onUpdateComplete", etc)
//   fpListener   : a pointer to the function which should fire in response to 
//                  objSource[sEventName]();
//   objScope     : the object whose scope fpListener should be run in when fired.
//   blnRunOnce   : flag that indicates whether the listener should automatically be removed after 
//                  it is first fired.
//
// Listener.remove(objSource, strEventNae, fpListener, objScope);


function Listener(fp, scope, removing, args) {
        this.fp = fp;
        this.scope = scope;
        this.removeing = removing;
}

Listener.add = function(oSource, sEvent, fpDest, oScope, bRunOnce) {
        if (!oSource[sEvent] || oSource[sEvent] == null || !oSource[sEvent]._listeners) {
                oSource[sEvent] = function() { Listener.fire(oSource, sEvent, arguments) };
                oSource[sEvent]._listeners = new Array();
        }

        var idx = this.findForEvent(oSource[sEvent], fpDest, oScope);
        if (idx == -1) idx = oSource[sEvent]._listeners.length;
        
        oSource[sEvent]._listeners[idx] = new Listener(fpDest, oScope, bRunOnce);
}

Listener.getLength = function(oSource, sEvent){
    if (oSource[sEvent] == null || oSource[sEvent]._listeners == null) 
        return 0;
    return oSource[sEvent]._listeners.length;
}

Listener.remove = function(oSource, sEvent, fpDest, oScope) {
        var idx = this.findForEvent(oSource[sEvent], fpDest, oScope);
        if (idx != -1) {
                var iLast = oSource[sEvent]._listeners.length - 1;
                oSource[sEvent]._listeners[idx] = oSource[sEvent]._listeners[iLast];
                oSource[sEvent]._listeners.length--;
        }
}

Listener.findForEvent = function(fpEvent, fpDest, oScope) {
        if (fpEvent._listeners) {
                for (var i = 0; i < fpEvent._listeners.length; i++) {
                        if (fpEvent._listeners[i].scope == oScope && fpEvent._listeners[i].fp == fpDest) {
                                return i;
                        }
                }
        }
        return -1;
}

Listener.fire = function(oSourceObj, sEvent, args) {
    
    if(oSourceObj && oSourceObj[sEvent] && oSourceObj[sEvent]._listeners) { // TRS 

		var lstnr, fp;
		var last = oSourceObj[sEvent]._listeners.length - 1;

		// must loop in reverse, because we might be removing elements as we go.

		for (var i = last; i >= 0; i--) {
			lstnr = oSourceObj[sEvent]._listeners[i];
			fp = lstnr.fp;
                
			fp.apply(lstnr.scope, args);

			if (lstnr.remove) Listener.remove(oSourceObj, sEvent, lstnr.fp, lstnr.scope);
		}
	}
	
	return(-1)
}

/**
    Kviečia įvykį pagal sąlygą. Jei p_blnShowObject == true tai iškviečia įvykius tik tai tam objektui,
    Jei p_blnShowObject == false, tai kviečia įvykius visiems kitiems objektams.
*/
Listener.fireConditional = function(oSourceObj, sEvent, args, p_objObject, p_blnShowObject) {
    
    if(oSourceObj && oSourceObj[sEvent] && oSourceObj[sEvent]._listeners) { // TRS 

		var lstnr, fp;
		var last = oSourceObj[sEvent]._listeners.length - 1;

		// must loop in reverse, because we might be removing elements as we go.

		for (var i = last; i >= 0; i--) {
			lstnr = oSourceObj[sEvent]._listeners[i];
			if (p_blnShowObject && lstnr.scope != p_objObject || !p_blnShowObject && lstnr.scope == p_objObject)
			    continue;
			fp = lstnr.fp;
                
			fp.apply(lstnr.scope, args);

			if (lstnr.remove) Listener.remove(oSourceObj, sEvent, lstnr.fp, lstnr.scope);
		}
	}
	
	return(-1)
}

// impliment function apply for browsers which don't support it natively
if (!Function.prototype.apply) {
        Function.prototype.apply = function(oScope, args) {
                var sarg = [];
                var rtrn, call;

                if (!oScope) oScope = window;
                if (!args) args = [];

                for (var i = 0; i < args.length; i++) {
                        sarg[i] = "args["+i+"]";
                }

                call = "oScope.__applyTemp__(" + sarg.join(",") + ");";

                oScope.__applyTemp__ = this;
                rtrn = eval(call);
                delete oScope.__applyTemp__;
                return rtrn;
        }
}


/** globalus clsEventManaging klasės objektas */
var g_objEventManager = new clsEventManaging();
//======================================================================================
// clsEventManaging
//======================================================================================
/**
    globalių eventų managemento klasė
    @version 1.0 2006.10.02
    @author Rytis Gasparavičius
    @class clsEventManaging
    @constructor
*/
function clsEventManaging() 
{
    /** esamo documento eventų managerio id */
    this.g_strId = null;
    /** tėvinio documento eventų managerio id */
    this.g_strParentId = '';
    /** vaikinių documentų eventų managerių id */
    this.g_arr_strChildId = new Array();
    /** nurodo ar jau uždėtas duotas eventas */
    this.g_bln_hshEventAdded = new Object(); 
    /** mouse eventų left koordinatė */ 
    this.g_intX = null;
    /** mouse eventų top koordinatė */ 
    this.g_intY = null;
    
    /** rodyklė į save*/
    var objThis = this;
    /** pagal eventus užhashuotos ir pagal funkcijų id užhashuotos funkcijos*/
    var hsh_hsh_Function = new Object();
    /** pagal eventus užhashintų funkcijų id */
    var hsh_arr_strFunctionId = new Object();
    /** nurodo ar hashintas eventas nukillintas */
    var hsh_blnEventKilled = new Object();
    /** saugo killinamų funkcijų id masyvą pagal duotą eventą*/
    var hsh_arr_strKilledFunctionId = new Object(); 
    
    
// PRIVATE METHODS

////////////////////////////////////////////////////////////////////////////////////////////////////
// REGISTERING
////////////////////////////////////////////////////////////////////////////////////////////////////     
    //------------------------------------------------------------------------------------
    /**
        metodas 'str_fRegisterChild' metodo pagalba sugeneruoja id esamam documentui užregistruoti
        @type str
    */
    this.str_fGetId = function() 
    {
        var strId = null;
        if(window.parent != window && window.parent.g_objEventManager != null)
        {
            strId = window.parent.g_objEventManager.str_fRegisterChild();
            return strId;
        }    
        else
            return 'parentDoc';        
    }
    //------------------------------------------------------------------------------------
    /**
        registers child document & returns id for child document, that was registered
    */ 
    this.str_fRegisterChild = function() 
    {
        var intChildLength = this.g_arr_strChildId.length;
        var strId = this.g_strId + '_' + intChildLength;
            this.g_arr_strChildId[intChildLength] = strId;
        return strId;
    }
    //------------------------------------------------------------------------------------
    /**
       metodas grazina child frame'o indexa
    */ 
    this.g_intGetChildIndex = function(p_strChildId)
    {
        if(cIE == true)
        {
            if(document.frames != null)
            {
                for(var i = 0; i < document.frames.length;i++) 
                {
                    if(document.frames[i].g_objEventManager != null)
                        if(document.frames[i].g_objEventManager.g_strId == p_strChildId)
                        {
                            return i;
                            break;  
                        }   
                }
            }
        }
        else if(cFF == true)
        {
            if(window.frames != null)
            {
                for(var i = 0; i < window.frames.length;i++) 
                {
                    if(window.frames[i].g_objEventManager != null)
                        if(window.frames[i].g_objEventManager.g_strId == p_strChildId)
                        {
                            return i;
                            break;
                        }    
                }
            }
        }
    }
    //------------------------------------------------------------------------------------
    /**
        setting xy by child obj
    */ 
    this.fSetXYByChild = function(p_strChildId) 
    {
        var objFrame = null;
        var objChildEventManager = null;
        if(cIE == true)
        {
            if(document.frames != null)
            {
                for(var i = 0; i < document.frames.length;i++) 
                {
                    if(document.frames[i].g_objEventManager != null)
                        if(document.frames[i].g_objEventManager.g_strId == p_strChildId)
                        {
                            objFrame = document.frames[i];
                            objChildEventManager = document.frames[i].g_objEventManager;
                            break;  
                        }   
                }
            }
        }
        else if(cFF == true)
        {
            if(window.frames != null)
            {
                for(var i = 0; i < window.frames.length;i++) 
                {
                    if(window.frames[i].g_objEventManager != null)
                        if(window.frames[i].g_objEventManager.g_strId == p_strChildId)
                        {
                            objFrame = window.frames[i];
                             objChildEventManager = window.frames[i].g_objEventManager;
                            break;
                        }    
                }
            }
        }
        var arrArg = objPosition(objFrame.frameElement);
        this.g_intX = arrArg[2] + objChildEventManager.g_intX;
        this.g_intY = arrArg[3] + objChildEventManager.g_intY;
    }
    //------------------------------------------------------------------------------------
    /** alerting parent about   @p_strEvent    event
       @param p_strChildId - objektas, kuris ishviete sy metoda
       @param p_strDocumentURL - 
    */ 
    this.fCallParent = function(p_strChildId, p_strEvent,p_objEvent,p_strDocumentURL, p_arrNavigation) 
    {
        var objParent = objThis.g_obj_fGetParent();
       
        if(objParent != null)
        {
            var intChildIndex = objParent.g_intGetChildIndex(p_strChildId);
            var arr_intCloneNav = g_obj_fClone(p_arrNavigation);
            arr_intCloneNav.splice(0, 0, intChildIndex);
            objParent.fSetXYByChild(p_strChildId);
            objParent.fHandleEvent(p_strEvent,p_objEvent,p_strDocumentURL,arr_intCloneNav);
            objParent.fCallChildren(p_strEvent,p_strChildId,p_objEvent,p_strDocumentURL,arr_intCloneNav);    
            objParent.fCallParent(objParent.g_strId, p_strEvent,p_objEvent,p_strDocumentURL,arr_intCloneNav);
        }
    }
    //------------------------------------------------------------------------------------
    /**
         setting xy for child obj by current obj(parent)
    */
    this.fSetXYByParent = function(p_strIgnoredId) 
    {
        var arr_objChild = objThis.g_arr_obj_fGetChild();
        if(arr_objChild != null)
        {
            for(var i = 0; i < arr_objChild.length; i++) 
            {
               if(arr_objChild[i].g_strId != p_strIgnoredId)
               {
                    
                    // getting objFrame && objChildEventManager by  objChildEventManager.g_strId
                    var objFrame = null;
                    var objChildEventManager = null;
                    if(cIE == true)
                    {
                        if(document.frames != null)
                        {
                            for(var y = 0; y < document.frames.length;y++) 
                            {
                                if(document.frames[y].g_objEventManager != null)
                                    if(document.frames[y].g_objEventManager.g_strId == arr_objChild[i].g_strId)
                                    {
                                        objFrame = document.frames[y];
                                        objChildEventManager = document.frames[y].g_objEventManager;
                                        break;  
                                    }   
                            }
                        }
                    }
                    else if(cFF == true)
                    {
                        if(window.frames != null)
                        {
                            for(var y = 0; y < window.frames.length;y++) 
                            {
                                if(window.frames[y].g_objEventManager != null)
                                    if(window.frames[y].g_objEventManager.g_strId == arr_objChild[i].g_strId)
                                    {
                                        objFrame = window.frames[y];
                                         objChildEventManager = window.frames[y].g_objEventManager;
                                        break;
                                    }    
                            }
                        }
                    }
                    var arrArg = objPosition(objFrame.frameElement);
                    
                    arr_objChild[i].g_intX = objThis.g_intX - arrArg[2];           
                    arr_objChild[i].g_intY = objThis.g_intY - arrArg[3];   
               }
            }
        }    
    }
    //------------------------------------------------------------------------------------
    /**
        suaktyvina 'child' documentų eventus
    */
    this.fCallChildren = function(p_strEvent, p_strIgnoredId, p_objEvent,p_strDocumentURL, p_arr_intNavigation)
    {
        var arr_objChild = objThis.g_arr_obj_fGetChild();
        if(arr_objChild.length > 0)
        {
            var arr_intCloneNav = g_obj_fClone(p_arr_intNavigation);
            arr_intCloneNav.splice(0, 0, -1);
            objThis.fSetXYByParent(p_strIgnoredId);
            for(var i = 0; i < arr_objChild.length; i++) 
            {
               if(arr_objChild[i].g_strId != p_strIgnoredId)
               {
                   
                   arr_objChild[i].fHandleEvent(p_strEvent, p_objEvent, p_strDocumentURL, arr_intCloneNav);
                   arr_objChild[i].fCallChildren(p_strEvent, null, p_objEvent, p_strDocumentURL, arr_intCloneNav);    
               }
            }
        }    
    }
////////////////////////////////////////////////////////////////////////////////////////////////////
// ADDING EVENTS
////////////////////////////////////////////////////////////////////////////////////////////////////       
    //------------------------------------------------------------------------------------
    /**
        uždeda eventą ant documento
    */
    this.fAddEventOnDoc = function(p_strEvent) 
    {
         addEvent(document,p_strEvent, fOnEvent);
         g_fRegisterObject(p_strEvent);
    }
    //------------------------------------------------------------------------------------
    /**
        uždeda eventą ant tėvinio documento
    */
    this.fAddEventOnParent = function(p_strChildId, p_strEvent) 
    {
        var objParent = objThis.g_obj_fGetParent();
        if(objParent != null)
        {
            objParent.g_bln_hshEventAdded[p_strEvent] = true;
            objParent.fAddEventOnDoc(p_strEvent);
            objParent.fAddEventOnChildren(p_strEvent,p_strChildId);    
            objParent.fAddEventOnParent(objParent.g_strId, p_strEvent);
        }
    }
    //------------------------------------------------------------------------------------
    /**
        uždeda eventą ant vaikinių documentų
    */
    this.fAddEventOnChildren = function(p_strEvent,p_strIgnoredId) 
    {
        var arr_objChild = objThis.g_arr_obj_fGetChild();
        if(arr_objChild != null)
        {
            for(var i = 0; i < arr_objChild.length; i++) 
            {
               if(arr_objChild[i].g_strId != p_strIgnoredId)
               {
                   arr_objChild[i].g_bln_hshEventAdded[p_strEvent] = true;
                   arr_objChild[i].fAddEventOnDoc(p_strEvent);
                   arr_objChild[i].fAddEventOnChildren(p_strEvent,null);    
               }
            }
        }    
    }
////////////////////////////////////////////////////////////////////////////////////////////////////
// NAVIGATION
//////////////////////////////////////////////////////////////////////////////////////////////////// 
    //------------------------------------------------------------------------------------
    /**
        grąžina tėvinio documento g_objEventManager objektą
        @type obj
    */
    this.g_obj_fGetParent = function() 
    {
      var a = window;
      var aparent = window.parent;
        if(window.parent != window)
        {
            return window.parent.g_objEventManager;
        }    
        else
        {
            return null;
        }    
    }
    //------------------------------------------------------------------------------------
    /**
        grąžina vaikinių documentų g_objEventManager objektus
        @type obj
    */
    this.g_arr_obj_fGetChild = function() 
    {
        var arr_objChild = new Array();
        if(cIE == true)
        {
            if(document.frames != null)
            {
                for(var i = 0; i < document.frames.length;i++) 
                {
                    if(document.frames[i].g_objEventManager != null)
                        arr_objChild.push(document.frames[i].g_objEventManager);
                }
            }
        }
        else if(cFF == true)
        {
            if(window.frames != null)
            {
                for(var i = 0; i < window.frames.length;i++) 
                {
                    if(window.frames[i].g_objEventManager != null)
                        arr_objChild.push(window.frames[i].g_objEventManager);
                }
            }
        }
        return arr_objChild;
    }
////////////////////////////////////////////////////////////////////////////////////////////////////
// EVENTS & EVENT HANDLERS
////////////////////////////////////////////////////////////////////////////////////////////////////    
    //-------------------------------------------------------------------------------------
    /**
        eventHandler of eventManager event
        @param p_strEvent evento tipas
        @param e HTML eventas
        @param p_strDocumentURL documento URL
    */
    this.fHandleEvent = function( p_strEvent, e, p_strDocumentURL, p_arr_intNavigation) 
    {
        if(hsh_hsh_Function[p_strEvent] != null)
        {
            var intTemp = hsh_arr_strFunctionId[p_strEvent].length - 1;
            for(var i = intTemp; i > -1; i--)
            {
                var hshArg = new Object();
                    hshArg['strFunctionId'] = hsh_arr_strFunctionId[p_strEvent][i]; 
                    hshArg['intX'] = objThis.g_intX;
                    hshArg['intY'] = objThis.g_intY;
                    hshArg['arr_intNavigation'] = p_arr_intNavigation;
                    hshArg['event'] = e;
                if(document.URL == p_strDocumentURL)
                    hshArg['blnEventOnCurrDoc'] = true;
                else
                    hshArg['blnEventOnCurrDoc'] = false; 
             // tikrinama ar eventas nenukillintas
                if(hsh_blnEventKilled[p_strEvent] == false)
                {
                 // kviečiamas handleris
                    if(hsh_hsh_Function[p_strEvent][hsh_arr_strFunctionId[p_strEvent][i]] != null)
                    {              
                       // if(p_strEvent == 'click')
                        hsh_hsh_Function[p_strEvent][hsh_arr_strFunctionId[p_strEvent][i]](e,hshArg);    
                    }   
                }       
             // jei eventas killinamas   
                else
                {
                 // jei nebuvo killinamos visos funkcijos, o tik duotas killinamų funkcijų sąrašas   
                    if(hsh_arr_strKilledFunctionId[p_strEvent] != null)
                    {
                        var blnFunctionFound = false;
                        for(var y = 0; y < hsh_arr_strKilledFunctionId[p_strEvent].length; y++)
                        {
                            if(hsh_arr_strKilledFunctionId[p_strEvent][y] == hsh_arr_strFunctionId[p_strEvent][i])
                            {
                                blnFunctionFound = true;
                                break;
                            }
                        }
                     // esama funkcija nerasta killinamų funkcijų sąraše
                        if(blnFunctionFound == false)
                        {
                         // kviečiamas handleris  
                            if(hsh_hsh_Function[p_strEvent][hsh_arr_strFunctionId[p_strEvent][i]] != null)
                            {              
                               hsh_hsh_Function[p_strEvent][hsh_arr_strFunctionId[p_strEvent][i]](e,hshArg);    
                            }   
                        }
                    }
                 // jei buvo killinamos visos funkcijos   
                    else
                    {
                        
                    }
                }
            }
            hsh_arr_strKilledFunctionId[p_strEvent] = null;
            hsh_blnEventKilled[p_strEvent] = false;
        }
    }
    //-------------------------------------------------------------------------------------
    /**
        eventHandler of HTML event
    */ 
    function fOnEvent(e) 
    {
          objThis.g_intX = e.clientX;    
          objThis.g_intY = e.clientY;
          var objDocument = null;
          var objTemp = getSrcElement(e);
          while(objTemp != null && objTemp != document) 
          {
              objTemp = objTemp.parentNode;
          }
          if(objTemp != null)
          {             
              objDocument = objTemp;          // sito documento URL eis per visus frame'us
                
              var arr_intNavigation = new Array();
              objThis.fHandleEvent(e.type, e, objDocument.URL,arr_intNavigation);
              objThis.fCallParent(objThis.g_strId, e.type, e, objDocument.URL,arr_intNavigation);
              objThis.fCallChildren(e.type, null, e, objDocument.URL,arr_intNavigation);
          }
    }
    //------------------------------------------------------------------------------------
 
   




// PUBLIC METHODS

////////////////////////////////////////////////////////////////////////////////////////////////////
// ADDING & REMOVING EVENTS
////////////////////////////////////////////////////////////////////////////////////////////////////    
    /**
        metodas uždeda globalų 'p_strEvent' eventą ant documento. užmountinama funkcija 'p_str_fFunction', kurios id = p_strId
        @param p_strId - skirtas objektu aptažinimui(funkcijos id)
        @param p_strId - skirtas objektu aptažinimui(funkcijos id)
        @param p_strId - skirtas objektu aptažinimui(funkcijos id)
    */ 
    this.g_fAddEvent = function(p_strId, p_strEvent, p_str_fFunction)
    {
        g_fRegisterObject(p_strEvent);
   // jei nebuvo sukurtas hashas pagal duotą eventą     
        if(hsh_hsh_Function[p_strEvent] == null)
        {
            hsh_hsh_Function[p_strEvent] = new Object();   
            hsh_arr_strFunctionId[p_strEvent] = new Array();   
        }    
   // nustatoma kad duotas eventas nenukillintas     
        hsh_blnEventKilled[p_strEvent] = false;
        
        hsh_hsh_Function[p_strEvent][p_strId] = p_str_fFunction;
        hsh_arr_strFunctionId[p_strEvent].push(p_strId);
        var objParent = this.g_obj_fGetParent();
        if(this.g_bln_hshEventAdded[p_strEvent] != true)  // tai reikia visiems uzdeti
        {
            this.g_bln_hshEventAdded[p_strEvent] = true;
            this.fAddEventOnParent(objThis.g_strId, p_strEvent);            
            this.fAddEventOnChildren(p_strEvent,null);
            addEvent(document, p_strEvent, fOnEvent);
        }
    }
      //-------------------------------------------------------------------------------------
    // p_strId - nuo kurio objekto remove'inti eventa
    this.g_fRemoveEvent = function(p_strId, p_strEvent) 
    {
        if(hsh_hsh_Function[p_strEvent] != null)
        {
            hsh_hsh_Function[p_strEvent][p_strId] = null;
            for(var i = 0; i < hsh_arr_strFunctionId[p_strEvent].length; i++)
            {
                if(hsh_arr_strFunctionId[p_strEvent][i] == p_strId)
                {
                    hsh_arr_strFunctionId[p_strEvent].splice(i,1);
                    return;
                }
            }
        }
    }
    //-------------------------------------------------------------------------------------
    /**
        killina eventą
        @param p_strEvent killinamas eventas
        @param p_arr_strId killinamas funkcijų id masyvas (jei == null, tai killinamos visos funkcijos)
    */
    this.g_fKillEvent = function(p_strEvent, p_arr_strId) 
    {
        hsh_blnEventKilled[p_strEvent] = true;
        if(p_arr_strId != null)
        {
         // jei nebuvo priskirta nei vienos killinamos funkcijos    
            if(hsh_arr_strKilledFunctionId[p_strEvent] == null)
            {
                hsh_arr_strKilledFunctionId[p_strEvent] = p_arr_strId;                           
            }
         // jei buvo priskirta killinamų funkcijų       
            else
            {
                hsh_arr_strKilledFunctionId[p_strEvent] = hsh_arr_strKilledFunctionId[p_strEvent].concat(p_arr_strId);
            }
        }
    }
    //-------------------------------------------------------------------------------------
    /**
        fire'ina eventą
        @param p_strEvent fire'inamas eventas
    */
    this.g_fFireEvent = function(p_strEvent, e) 
    {
         objThis.g_intX = e.clientX;
         objThis.g_intY = e.clientY;
         var objDocument = null;
         var objTemp = getSrcElement(e);
         while(objTemp != null && objTemp != document) 
         {
             objTemp = objTemp.parentNode;
         }
         if(objTemp != null)
         {             
             objDocument = objTemp;          // sito documento URL eis per visus frame'us
             var arr_intNavigation = new Array();
             objThis.fHandleEvent(p_strEvent, e, objDocument.URL,arr_intNavigation);
             objThis.fCallParent(objThis.g_strId, p_strEvent, e, objDocument.URL,arr_intNavigation);
             objThis.fCallChildren(p_strEvent, null, e, objDocument.URL,arr_intNavigation);
         }
    }
    //-------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////////////
// HTML EVENT DESTRUCTOR 
//////////////////////////////////////////////////////////////////////////////////////////////////// 
    var g_arr_strRegister = new Array(); // Visu laiku u?detu eventu sara?as
    /*
        RS 2006.06.21
        @p_strId - Stringas kuri norime isiminti.
        Metodas isimena tik skirtingus jam paduotus stringus. Veliau jie bus panaudoti nuimant
        visus eventus nuo document.
    */
    function g_fRegisterObject(p_strId)
    {
        for(var i = 0;i < g_arr_strRegister.length;i++)
        {
            if(g_arr_strRegister == p_strId)
                return;
        }
        g_arr_strRegister.push(p_strId);
    }
    //-------------------------------------------------------------------------------------
    /*
        RS 2006.06.21
        I?valo visus kada nors u?detus eventus, per globalu eventu u?dejika 
        (originaliai u?detus ?itame ar kituose documentuose).
    */
    addEvent(window, 'unload', fDestructor);
    function fDestructor(e)
    {
        for(var i = 0; i < g_arr_strRegister.length; i++)
        {
            removeEvent(document, g_arr_strRegister[i], fOnEvent);
        }
        removeEvent(window, 'unload', fDestructor);
    }
    //-------------------------------------------------------------------------------------
// end  PUBLIC METHODS


 
  if(window.parent != window  && window.parent.g_objEventManager != null)
        this.g_strParentId = window.parent.g_objEventManager.g_strId;
    this.g_strId = this.str_fGetId();
//checking if parent has added events
    var objParent = this.g_obj_fGetParent();
    if(objParent != null)               
    {
        for(var i in objParent.g_bln_hshEventAdded)
        {
            if(objParent.g_bln_hshEventAdded[i] == true)  // if parent has added event then child adds event as well
            {
                this.g_bln_hshEventAdded[i] = true;
                this.fAddEventOnDoc(i);
            }    
        }
    }

}
//======================================================================================
// end clsEventManaging
//======================================================================================



// Įvykių uždėjimo funkcijos \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\



//<><><>////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////                                                 ///////////////
////////////////                  AJAX funkcijos                 ///////////////
////////////////                                                 ///////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


//---------------------------------------------------------------------
/**
    Asinchroniskai(nelaukia rezultatu) daro requesta.
    @param p_strUrl serverio adresas
    @param p_strData siun?iami duomenys
    @param p_fAfterDataArrived funkcija kuri bus i?kviesta gavus atsakym? i? serverio
*/
function call(p_strUrl, p_strData, p_fAfterDataArrived)
{
	var pageUrl = p_strUrl + "?call=true";
	if (window.XMLHttpRequest)
	{
	    var objXmlCall;
		objXmlCall = new XMLHttpRequest();
		objXmlCall.onreadystatechange = p_fAfterDataArrived;
		objXmlCall.open("POST", pageUrl, true);
		objXmlCall.send(p_strData);
	}
	else if (window.ActiveXObject)
	{
	    var objXmlCall;
		objXmlCall = new ActiveXObject("Microsoft.XMLHTTP")
		if (objXmlCall)
		{
			objXmlCall.onreadystatechange = p_fAfterDataArrived;
			objXmlCall.open("POST", pageUrl, true);
			objXmlCall.send(p_strData);
		}
	}
}
//---------------------------------------------------------------
/**
    Sinchroniškai (laukia rezultatų) daro requestą.
    @param p_strUrl serverio adresas
    @param data siunčiami duomenys
    @param funkcija funkcija kuri bus iškviesta gavus atsakymą iš serverio
    @returns serverio atsakymas
    @type string
*/
function call2(p_strUrl, p_strData)
{
    var objXmlCall;
	var pageUrl = p_strUrl + "?call=true";
    if (window.XMLHttpRequest)
	{
		objXmlCall = new XMLHttpRequest();
		objXmlCall.open("POST", pageUrl, false);
		objXmlCall.send(p_strData);
		return(objXmlCall.responseText);
	}
	else
	if (window.ActiveXObject)
	{
		objXmlCall = new ActiveXObject("Microsoft.XMLHTTP");
		objXmlCall.open("POST", pageUrl, false);
		objXmlCall.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		objXmlCall.send( p_strData );
		return(objXmlCall.ResponseText);
	}
}


// AJAX funkcijos \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

//<><><>////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////                                                 ///////////////
////////////////          XML manipuliavimo funkcijos            ///////////////
////////////////                                                 ///////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

/** 
    Xml'inę eilutę užkrauna į xml dokumentą.
    @param p_strText xml'inė eilutė.
    @returns Užloadintą xml dokumentą arba null jei įvyko klaida loadinant
    @type HTMLdocument 
*/
function getXml(p_strText)
{
    var objXmlDOM;
    var strTemp = "" + p_strText.replace(/&(?!(quot;|apos;|amp;|lt;|gt;))/g, '&amp;');
    if (window.ActiveXObject)
    {
        objXmlDOM = new ActiveXObject("MSXML2.DOMDocument");
        objXmlDOM.loadXML(strTemp);
        objXmlDOM.setProperty("SelectionLanguage", "XPath");
        if (objXmlDOM.parseError.errorCode != 0)
        {
            console("Error parsing xml: \n" + strTemp + '_');
            console(objXmlDOM.parseError.errorCode);
            console(objXmlDOM.parseError.reason);
            console(objXmlDOM.parseError.line);
            if (strTemp.search('var blnLoginPage = true;') > -1)
                window.location = window.location;
                //g_fRedirectToPage('Login.aspx');
            if (g_objLoadingIndicator && g_objLoadingIndicator.g_fHide)
                g_objLoadingIndicator.g_fHide();
            return(null);
        }
    }
    else 
    {
        objXmlDOM = (new DOMParser).parseFromString(strTemp, "text/xml");
        objXmlDOM.normalize(); // DA tam kad sujungtu suskaidytas dalis po 4096 simbolius
        if(objXmlDOM.documentElement && objXmlDOM.documentElement.nodeName == "parsererror")
        {
            console("Error parsing xml: \n" + strTemp);
            if (strTemp.search('var blnLoginPage = true;') > -1)
                window.location = window.location;
                //g_fRedirectToPage('Login.aspx');
            if (g_objLoadingIndicator && g_objLoadingIndicator.g_fHide)
                g_objLoadingIndicator.g_fHide();
            return(null);
        }
    }
    return(objXmlDOM);     
}
//---------------------------------------------------------------
/**
    Iš HMTLDocumento padaro stringą.
    @param HTMLdocument
    @return xml stringą
    @type string
*/
function g_str_fSerializeXml(p_objXmlDoc)
{
    if(p_objXmlDoc.xml)
    {
        return(p_objXmlDoc.xml);
    }
    else
    {
        var objSerializer = new XMLSerializer();
        var strAts = objSerializer.serializeToString(p_objXmlDoc);
        return(strAts);
    }
}
//---------------------------------------------------------------
/**
    Gražina objekto pirmo lygio vaikų masyvą , galima nurodyti vaikų tipą,
    Tipai :<br>
    1 ELEMENT_NODE <br>
    2 ATTRIBUTE_NODE <br>
    3 TEXT_NODE <br>
    4 CDATA_SECTION_NODE <br>
    5 ENTITY_REFERENCE_NODE <br>
    6 ENTITY_NODE <br>
    7 PROCESSING_INSTRUCTION_NODE <br>
    8 COMMENT_NODE <br>
    9 DOCUMENT_NODE <br>
    10 DOCUMENT_TYPE_NODE <br>
    11 DOCUMENT_FRAGMENT_NODE <br>
    12 NOTATION_NODE
    @param p_objElement HTML elementas kurio vaikus filtruosime
    @param p_intType Vaikų tipas , pagal kurį bus filtruojama (default 1)
    @returns Nufiltruotą vaikų masyvą
    @type HTMLElement[]
*/
function getChildren(p_objElement, p_intType)
{
	var intType = 1; 
	if(p_intType != null)intType = p_intType;
	var arr_objChildren = new Array();
	if(p_objElement != null && p_objElement.childNodes != null)
	{
	    var objNodes = p_objElement.childNodes;
	    for(var i = 0;i < objNodes.length;i++)
	    {
		    if(objNodes[i].nodeType == intType)
		    {
			    arr_objChildren.push(objNodes[i]);
		    }
	    }
	}
	return(arr_objChildren);
}

/**
    Iš xml objekto išgauna hashų masyvą. Laukus atsirenka pati.
*/
function g_arr_hsh_fHashArrayFromXml(p_objXml)
{
    var arrChld = getChildren(p_objXml);
    arrChld = getChildren(arrChld[0]);
    
	var arr_hshResultArray = new Array();
    for (var j = 0; j < arrChld.length; j++)    // Per eilutes
    {
	    arrChld2 = getChildren(arrChld[j]);
	    var objRow = new Object();
	    for (var k = 0; k < arrChld2.length; k++)   // Per stulpelius
	    {
	        if(arrChld2[k].firstChild != null)
		        objRow[arrChld2[k].tagName] = arrChld2[k].firstChild.nodeValue;
		    else
		        objRow[arrChld2[k].tagName] = '';
		}
		arr_hshResultArray.push(objRow);
    }
    return arr_hshResultArray;    
}

if( document.implementation.hasFeature("XPath", "3.0") )
{
	if(!XMLDocument) // Čia Operai
	{
        var XMLDocument = Document;
    }
	XMLDocument.prototype.selectNodes = function(cXPathString, xNode)
	{
		if( !xNode ) { xNode = this; } 

		var oNSResolver = this.createNSResolver(this.documentElement)
		var aItems = this.evaluate(cXPathString, xNode, oNSResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null)
		var aResult = [];
		for( var i = 0; i < aItems.snapshotLength; i++)
		{
			aResult[i] =  aItems.snapshotItem(i);
		}
		
		return aResult;
	}
	XMLDocument.prototype.selectSingleNode = function(cXPathString, xNode)
	{
		if( !xNode ) { xNode = this; } 

		var xItems = this.selectNodes(cXPathString, xNode);
		if( xItems.length > 0 )
		{
			return xItems[0];
		}
		else
		{
			return null;
		}
	}

	Element.prototype.selectNodes = function(cXPathString)
	{
		if(this.ownerDocument.selectNodes)
		{
			return this.ownerDocument.selectNodes(cXPathString, this);
		}
		else{throw "For XML Elements Only";}
	}

	Element.prototype.selectSingleNode = function(cXPathString)
	{	
		if(this.ownerDocument.selectSingleNode)
		{
			return this.ownerDocument.selectSingleNode(cXPathString, this);
		}
		else{throw "For XML Elements Only";}
	}

}

/**
    Gauna XML nodo aprašą su vidumi.
    KM 07.06.26
*/
if (cFF)    // FF
{
    g_str_fOuterXML = function(p_objNode)
    {
        if (!p_objNode || (p_objNode.constructor != Element && p_objNode.constructor != XMLDocument))
        {
            return '';    
        } 
        return (new XMLSerializer()).serializeToString(p_objNode);    
    }
}
else
if (cIE)
{
    g_str_fOuterXML = function(p_objNode)
    {
        if (!p_objNode || !p_objNode.xml)
        {
            return '';
        }
        return p_objNode.xml;   
    }
}


/**
    Gauna XML nodo vidų.
    KM 07.06.26
*/
function g_str_fInnerXML(p_objNode)
{
    var strResult = '';
    if (!p_objNode || !p_objNode.childNodes)
        return strResult;
    var arr_objChildren = p_objNode.childNodes;    
    for (var i = 0, intLength = arr_objChildren.length; i < intLength; i++)
    {
        strResult += g_str_fOuterXML(arr_objChildren[i]);
    } 
    return strResult;        
}

// XML manipuliavimo funkcijos \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

//<><><>////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////                                                 ///////////////
////////////////              Eilučių funkcijos                  ///////////////
////////////////                                                 ///////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

/**
    Panaikina tusčius tarpus eilutės galuose.
    @addon
*/
String.prototype.trim = function()
{
	var x = this;
	x = x.replace(/^\s*(.*)/, "$1");
	x = x.replace(/(.*?)\s*$/, "$1");
	return x;
}
//---------------------------------------------------------------
/**
    Panaikina tusčius tarpus eilutės pradžioje.
    @addon
*/
String.prototype.trimLeft = function()
{
 var x = this;
 x = x.replace(/^\s*(.*)/, "$1");
 return x;
}
//---------------------------------------------------------------
/**
    Panaikina tusčius tarpus eilutės gale.
    @addon
*/
String.prototype.trimRight = function()
{
 var x = this;
 x = x.replace(/(.*?)\s*$/, "$1");
 return x;
}
//---------------------------------------------------------------
/**
    Reversina eilutę.
    @addon
*/
String.prototype.reverse = function() 
{
    var strAts = "";
    for (var i = this.length; i > 0; --i) 
    {
        strAts += this.charAt(i - 1);
    }
    return(strAts);
}

/* naudojami teksto kodavimui/atkodavimui perduodant per GET, jei perduodam i Domo dialoga, koduoti du kartus! */
function encode(p_strText)
{
	return(encodeURIComponent(p_strText));
}
function decode(p_strText)
{
	return(decodeURIComponent(p_strText));
}
/**
    KM 2006-07-19
    Vietoj po nurodyto simbolio ar eilutes prideda žodžio kelimo taga
*/
function g_str_fAddWordWraping(p_strWord, p_strCharacter)
{
    var objRegExp = new RegExp(p_strCharacter, 'g');    
    return p_strWord.replace(objRegExp, p_strCharacter+'<wbr>');    
}
/**
    Suskaido eilutes į tokias dalis - bendra pradžia, bendras galas, skirtinga A eilutės dalis, skirtinga B eilutės dalis.
    Betkuri iš šių dalių gali būti lygi ''.
    Šias dalis surašo į hashą ir grąžina tokiu pavidalu:
        {
            strBegin: bendra pradžia,
            strEnd: bendras galas,
            strDiffA: skirtinga A eilutės dalis,
            strDiffB: skirtinga B eilutės dalis
        }
    Operacija yra O(n) sudėtingumo, kur n = strBegin.length + strEnd.length;
    @param p_strA - Eilutė A;
    @param p_strB - Eilutė B;
*/
function p_hsh_fGetStringDifference(p_strA, p_strB)
{
    var i = 0;
    var intLengthA = p_strA.length;
    var intLengthB = p_strB.length;
    for (; i < intLengthA && i < intLengthB; i++)
    {
        if (p_strA.charAt(i) != p_strB.charAt(i))
            break;    
    }
    var intBeginLength = i;
    var intIndA = intLengthA - 1;
    var intIndB = intLengthB - 1;
    for (; intIndA >= intBeginLength && intIndB >= intBeginLength; )
    {
        if (p_strA.charAt(intIndA) != p_strB.charAt(intIndB))
            break;
        intIndA--;
        intIndB--;  
    }
    intIndA++;
    intIndB++; 
    return {
        strBegin: p_strA.substr(0,intBeginLength),
        strEnd: p_strA.substr(intIndA),
        strDiffA: p_strA.substr(intBeginLength, intIndA - intBeginLength),
        strDiffB: p_strB.substr(intBeginLength, intIndB - intBeginLength)};
}

/**
    Suskaido eilutes į tokias dalis - bendra pradžia, bendras galas, skirtinga A eilutės dalis, skirtinga B eilutės dalis.
    Betkuri iš šių dalių gali būti lygi ''.
    Šias dalis surašo į hashą ir grąžina tokiu pavidalu:
        {
            strBegin: bendra pradžia,
            strEnd: bendras galas,
            strDiffA: skirtinga A eilutės dalis,
            strDiffB: skirtinga B eilutės dalis
        }
    Operacija yra O(n) sudėtingumo, kur n = strBegin.length + strEnd.length;
    @param p_strA - Eilutė A;
    @param p_intCursorPosition - kursoriaus pozicija eilutėje A.
    @param p_strB - Eilutė B;
*/
function p_hsh_fGetStringDiffWithCursor(p_strA, p_intCursorPosition, p_strB)
{
    var i = 0;
    var intLengthA = p_strA.length;
    var intLengthB = p_strB.length;
    var intMaxA = Math.min(p_intCursorPosition, intLengthA);
    var intMaxB = intLengthB - (intLengthA - p_intCursorPosition);
    var intMaxi = Math.min(intMaxA, intMaxB);  
    for (; i < intMaxi; i++)
    {
        if (p_strA.charAt(i) != p_strB.charAt(i))
            break;    
    }
    var intBeginLength = i;
    return {
        strBegin: p_strA.substr(0,intBeginLength),
        strEnd: p_strA.substr(intMaxA),
        strDiffA: p_strA.substr(intBeginLength, intMaxA - intBeginLength),
        strDiffB: p_strB.substr(intBeginLength, intMaxB - intBeginLength)};
}

/**
    Pagal paduota hash objekta suformuoja URL parametru eilute - '?[param1]=[val1]&[param2]=[val2]&...'
    @param p_hshInput duomen? hashas
    @returns suformuot? duomen? eilut?, skirt? perduoti per GET
    @type string
*/
function g_str_fBuildURLParameterString(p_hshInput)
{
    var strParameters = '';
    for(strKey in p_hshInput)
    {
        if (strParameters == '')
            strParameters += '?';    
        else
            strParameters += '&';       
        strParameters += strKey + '=' + encode(p_hshInput[strKey]);
    }
    return strParameters;
}
//--------------------------------------------------------------------------------------
function g_hsh_fDecodeURLParameterString(p_strParameterString)
{
    var hshAts = new Object();
    var arr_strPairs = p_strParameterString.split('?')[1].split('&');
    for(var i = 0;i < arr_strPairs.length;i++)
    {
        var arr_strItems = arr_strPairs[i].split('=');
        hshAts[arr_strItems[0]] = decode(arr_strItems[1]);
    }
    return(hshAts);
}

/**
    Paduotą kelią išskaido į direktoriją ir failo vardą.
    @param p_strPath kelias iki failo
    @param p_strDelimiter skirtukas pagal kurį skaidyti
    @returns Grąžinamas formatas [direktorija, failoVardas]
    @type string[]
*/
function g_str_fSplitPath(p_strPath, p_strDelimiter)
{
    var arr_strTokens = p_strPath.split(p_strDelimiter);
	var strFileName = arr_strTokens[arr_strTokens.length - 1];
	var strPath = p_strPath.substring(0, p_strPath.length - strFileName.length); 
    return [strPath, strFileName];
}

/**
    Iš pilno failo kelio gauna failo pavadinimą.
    @param p_strPath Kelias iki failo. 
*/
function g_str_fGetFileName(p_strPath)
{
    if (p_strPath.indexOf('\\') != -1)
    {
        var arr_strTokens = p_strPath.split('\\');
	    return arr_strTokens[arr_strTokens.length - 1]; 	    
    }
    else if (p_strPath.indexOf('/') != -1)
    {
        var arr_strTokens = p_strPath.split('/');
	    return arr_strTokens[arr_strTokens.length - 1]; 
    }
    else
        return p_strPath;
}

/**
    Funkcija, kuri verčia int reikšmę į stringą pridedant 'px'. Jei reikšmė yra eilutė, su px,
    tai nieko nepakeičia.
    @param p_intValue{string}{number} Reikšmė, kurią reikia paversti.
    @returns Eilutę su pridėtu px.
*/
function g_str_fIntToPx(p_intValue)
{
    return parseInt(p_intValue) + 'px';
}

function g_str_fEscapeForXml(p_strValue)
{
    return p_strValue.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/\'/g, '&apos;');      
}

function g_str_fUnescapeFromXml(p_strValue)
{
    if (!p_strValue)
        return '';
    return p_strValue.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&apos;/g, '\'').replace(/&quot;/g, '"').replace(/&amp;/g, '&');      
}

/**
    Išmatuoja teksto plotį.
*/
function g_int_fGetTextWidth(p_strText, p_strClassName)
{
    var objElement = document.createElement('SPAN'); 
    objElement.innerHTML = '<nobr>' + p_strText + '</nobr>';
    objElement.style.position = 'absolute';
    if (p_strClassName)
        objElement.className = p_strClassName;
    document.body.appendChild(objElement);
    var intWidth = objElement.offsetWidth;
    document.body.removeChild(objElement);
    return intWidth;    
}   

/**
    Gauna kiekvieno simbolio kodą eilutėje.
    @param p_strText - eilutė;
    @returns int[] - kodų masyvą.
*/
function g_arr_int_fGetCharCodes(p_strText)
{
    var arr_intReturn = [];
    if (!p_strText || !p_strText.charCodeAt)
        return arr_intReturn;
    for (var i = 0, intLength = p_strText.length; i < intLength; i++)
    {
        arr_intReturn[i] = p_strText.charCodeAt(i);
    }
    return arr_intReturn;
}

/**
    Padaugina eilutę iš nurodyto skaičiaus t.y. sujungia tiek p_strString eilučių, kiek 
    nurodyta p_intCount parametru. Reikia pridėti 1, nes elementai apjunginėjami tik viduje.
*/
function g_str_fGetJoinedString(p_strString, p_intCount)
{
    return new Array(p_intCount + 1).join(p_strString);
}

/**
    Iš into padaro stringą reikiamo ilgio.
*/
function g_str_fPadIntToRequestedLength(p_intItem, p_intRequestedLength, p_strPad)
{
    var strStringFromInt = p_intItem.toString();
    var intDiff = p_intRequestedLength - strStringFromInt.length;
    if (intDiff < 0)
    {
        return strStringFromInt.substr(-p_intRequestedLength);
    }
    else
    {
        return g_str_fGetJoinedString(p_strPad, intDiff) + strStringFromInt;   
    }    
}

function g_str_fGetLocalizedId(p_strId)
{
    var intLast = p_strId.lastIndexOf('_');
    if (intLast < 0)
        return p_strId;
    else
        return p_strId.substr(intLast + 1);
}

/**
    Is URL stringo sukonstruoja parametru hasha
    @author VU
    @param {string} p_strUrl URL stringas
    @return parametru hashas
 */
function g_hsh_fParseUrl(p_strUrl)
{
    var hshParams = {};
    if(p_strUrl != '' && p_strUrl != null)
    {
        var arr_strParams = p_strUrl.split('&');
        var intCount = arr_strParams.length;
        for(var i = 0; i < intCount-1; i++)
        {
            var arr_strMas = arr_strParams[i+1].split('=');
            hshParams[arr_strMas[0]] = arr_strMas[1];
        }
    }
    return hshParams;
}

/**
    Is parametru hasho sukonstruoja URL stringa
    @author VU
    @param {hash} p_hshParams parametru hashas
    @return URL string
 */
function g_str_fFormatUrl(p_hshParams)
{
    var strUrl = '';
    if(p_hshParams != null)
    {
        for(i in p_hshParams)
        {
            strUrl += '&';
            strUrl += i + '=';
            strUrl += decode(p_hshParams[i]);
        }
        strUrl += ';';
    }
    return strUrl;
}

// Eilučių funkcijos \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

//<><><>////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////                                                 ///////////////
////////////////     Įvairių duomenų struktūrų funkcijos         ///////////////
////////////////                                                 ///////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

/**			
	Pagal duota formatą bando nuskaityti datos eilutę ir užloadinti į Date objektą bei jį gražinti.
	2007.03.14 įvestas pataisymas, kad jei paduodamas metų skaičiukas iš dviejų skaičių 
	(tiksliau .trim() duoda eilutę iki dviejų skaičių), tai parsina tokių būdu - jei metai yra didesni 
	už šios dienos metus + 20, tai data yra praėjusio amžiaus, jei ne, tai data yra šio amžiaus.
	@param p_strDate datos eilutė.
	@param p_strFormat  formatas, pvz MM/dd/yyyy
	@returns suformuotą datos objektą
	@type Date
*/
function g_obj_fGetDate(p_strDate, p_strFormat)
{
	if(p_strDate == null) 
	    return null;
	
	var strTemp = '';
	
	var intPradzia = p_strFormat.indexOf('d')
	var intPabaiga = p_strFormat.lastIndexOf('d') + 1;
	var strEil = p_strDate.substring(intPradzia, intPabaiga).trim();
	strEil = strEil.replace(/^(0*)/,'').replace(/[\D]/g,'0');
		
	strTemp += strEil + '.';
	var intDienos = parseInt(strEil);	
	intPradzia = p_strFormat.indexOf('M')
	intPabaiga = p_strFormat.lastIndexOf('M') + 1;
	strEil = p_strDate.substring(intPradzia, intPabaiga).trim();
	strEil =  strEil.replace(/^(0*)/,'').replace(/[\D]/g,'0');
	strTemp += strEil + '.';
	var intMenesiai = parseInt(strEil);		
	intPradzia = p_strFormat.indexOf('y');
	intPabaiga = p_strFormat.lastIndexOf('y') + 1;
	strEil = p_strDate.substring(intPradzia, intPabaiga);
    var strTempString = strEil;
    var index = strEil.search(/[0,1,2,3,4,5,6,7,8,9]/g);
    // Versija po 2007.03.14
    var strTrimed = strEil.trim();
    if (strTrimed.length <= 2)
    {
        var objTodaysDate = new Date();
        var intFullYears = objTodaysDate.getFullYear();
        var intYears = intFullYears % 100;
        var intMetai = parseInt(strEil);    
        if (intMetai > intYears + 20)
        {
            intMetai = intFullYears - intYears + intMetai - 100;   
        }
        else
        {
            intMetai = intFullYears - intYears + intMetai;        
        }
    }
    else
    {
        strEil = strEil.replace(/^[\D]/,'2').replace(/^(0*)/,'').replace(/[\D]/g,'0');
	    var intMetai = parseInt(strEil);
	}
    strTemp += strEil + '.';
	    
//    Versija pries 2007.03.14
//	strEil = strEil.replace(/^[\D]/,'2').replace(/^(0*)/,'').replace(/[\D]/g,'0');
//	strTemp += strEil + '.';
//	var intMetai = parseInt(strEil);
	
	
//RG 08 23  
	if(index == -1)
	    intMetai = '2000'; // ištaisiau į 2000, buvo aadf   KM 2007.03.13 
//end  RG 08 23 	    
	intPradzia = p_strFormat.indexOf('H');
	intPabaiga = p_strFormat.lastIndexOf('H') + 1;
	strEil = p_strDate.substring(intPradzia, intPabaiga);
	strEil = strEil.replace(/^(0)/,'');
	strTemp += strEil + '.';
	var intValandos = parseInt(strEil);
	
	intPradzia = p_strFormat.indexOf('m');
	intPabaiga = p_strFormat.lastIndexOf('m') + 1;
	strEil = p_strDate.substring(intPradzia, intPabaiga);
	strEil = strEil.replace(/^(0)/,'');
	strTemp += strEil + '.';
	var intMinutes = parseInt(strEil);
	
	intPradzia = p_strFormat.indexOf('s');
	intPabaiga = p_strFormat.lastIndexOf('s') + 1;
	strEil = p_strDate.substring(intPradzia, intPabaiga);
	strEil = strEil.replace(/^(0)/,'');
	strTemp += strEil + '.';
	var intSekundes = parseInt(strEil);
	if(isNaN(intDienos) == false || isNaN(intMenesiai) == false ||  isNaN(intMetai) == false  || isNaN(intValandos) == false || isNaN(intMinutes) == false || isNaN(intSekundes) == false)
	{
	    if( isNaN(intDienos) ) intDienos = '01';
	    if( isNaN(intMenesiai) ) intMenesiai = '01';
	    if( isNaN(intMetai) ) intMetai = '2000';
	    if( isNaN(intValandos) ) intValandos = '00';
	    if( isNaN(intMinutes) ) intMinutes = '00';
	    if( isNaN(intSekundes) ) intSekundes = '00';
    	
    	var objData = new Date( intMenesiai + '/' + intDienos + '/' + intMetai + ' ' + intValandos + ':' + intMinutes + ':' + intSekundes);
	    return(objData);
	}
	else
	    return null;
}

var g_objDateTimeFormat = {};

g_objDateTimeFormat.cMONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July','August', 'September', 'October', 'November', 'December'];
g_objDateTimeFormat.cDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday','Thursday', 'Friday', 'Saturday'];
g_objDateTimeFormat.cSUFFIXES = [	'st','nd','rd','th','th','th','th','th','th','th',
						'th','th','th','th','th','th','th','th','th','th',
						'st','nd','rd','th','th','th','th','th','th','th','st' ];

//-------------------------------------------------------
g_objDateTimeFormat.g_str_fFormat = function(p_objDate, p_strFormat) 
{
	var formatted     = ( p_strFormat != null ) ? p_strFormat : 'dd-mm-yy';
	var letters       = 'dMyHDhmst'.split('');
	var temp          = new Array();
	var count         = 0;
	var regexA;
	var regexB        = /\[(\d+)\]/;

	var day           = p_objDate.getDay();
	var date          = p_objDate.getDate();
	var month         = p_objDate.getMonth();
	var year          = p_objDate.getFullYear().toString();
	var hours         = p_objDate.getHours();
	var minutes       = p_objDate.getMinutes();
	var seconds       = p_objDate.getSeconds();

	var formats       = new Object();
	formats[ 'd' ]    = date;
	formats[ 'D' ]    = date + this.cSUFFIXES[ date - 1 ];
	formats[ 'dd' ]   = ( date < 10 ) ? '0' + date : date;
	formats[ 'ddd' ]  = this.cDAYS[ day ].substring( 0, 3 );
	formats[ 'dddd' ] = this.cDAYS[ day ];
	formats[ 'M' ]    = month + 1;
	formats[ 'MM' ]   = g_str_fApplyFormat('ss','@','0','' + (month + 1));
	formats[ 'MMM' ]  = this.cMONTHS[ month ].substring( 0, 3 );
	formats[ 'MMMM' ] = this.cMONTHS[ month ];
	formats[ 'y' ]    = ( year.charAt( 2 ) == '0' ) ? year.charAt( 3 ) : year.substring( 2, 4 );
	formats[ 'yy' ]   = year.substring( 2, 4 );
	formats[ 'yyyy' ] = g_str_fApplyFormat('ssss','@','0',year);
	formats[ 'H' ]    = hours;
	formats[ 'HH' ]   =  g_str_fApplyFormat('ss','@','0','' + hours);
	formats[ 'h' ]    = ( hours > 12 || hours == 0 ) ? Math.abs( hours - 12 ) : hours;
	formats[ 'hh' ]   =  g_str_fApplyFormat('ss','@','0','' + formats[ 'h' ]);
	formats[ 'm' ]    = minutes;
	formats[ 'mm' ]   = g_str_fApplyFormat('ss','@','0','' + minutes);
	formats[ 's' ]    = seconds;
	formats[ 'ss' ]   = g_str_fApplyFormat('ss','@','0','' + seconds);
	formats[ 't' ]    = ( hours < 12 ) ?  'A' : 'P';
	formats[ 'tt' ]   = ( hours < 12 ) ?  'AM' : 'PM';

	for ( var i = 0; i < letters.length; i++ ) 
	{
		regexA = new RegExp( '(' + letters[ i ] + '+)' );
		while ( regexA.test( formatted ) ) 
		{
			temp[ count ] = RegExp.$1;
			formatted = formatted.replace( RegExp.$1, '[' + count + ']' );
			count++;
		}
	}
	while ( regexB.test( formatted ) ) 
	{
		formatted = formatted.replace( regexB, formats[ temp[ RegExp.$1 ] ] );
	}
	return formatted;
}
//-------------------------------------------------------

/**
	Metodas formatuoja tekstą pagal nurodytą formatą.
	@param p_strText tekstas kurį formatuosim
	@p_strFormat formatas kurį taikysim tekstui<br>
	<pre>
		s - skaicius, c - raide;
		pvz: IP sss.sss.sss.sss
    </pre>
	@param p_strDelimiter nurodomas skirtukas formate
	@param p_strEmptyDelimiter nurodoma kokį simbolį įrašyti į formato vietą kurioje nėra simbolio
*/
function g_str_fApplyFormat(p_strFormat, p_strDelimiter, p_strEmptyDelimiter, p_strText)
{
	var arr_strDalys = p_strText.split(p_strDelimiter);
	var intDalis = 0;
	var intDaliesKuris = 0;
	var strFormattedString = '';
	var strFormatuotaDalis = '';
	for(var i = 0;i < p_strFormat.length;i++)
	{
		if(p_strFormat.charAt(i) == p_strDelimiter)
		{
			intDalis++;
			intDaliesKuris = 0;
			strFormattedString += strFormatuotaDalis + p_strDelimiter;
			strFormatuotaDalis = '';
		}
		else
		if(arr_strDalys[intDalis].length > intDaliesKuris)
		{
			strFormatuotaDalis += arr_strDalys[intDalis].charAt(intDaliesKuris);
			intDaliesKuris++;
		}
		else
		{
			if(p_strFormat.charAt(i) == 's')
			{
				strFormatuotaDalis = p_strEmptyDelimiter + strFormatuotaDalis;
			}
			else if(p_strFormat.charAt(i) == 'c')
			{
				strFormatuotaDalis += p_strEmptyDelimiter;
			}
		}
	}
	strFormattedString += strFormatuotaDalis;
	return(strFormattedString);
}
//-------------------------------------------------------

/**
    Iš seno formato gauna naują formatą.
    @param p_strDate Data užrašyta eilute.
    @param p_strOldFormat Datos formatas iš kurio reikia transformuoti.
    @param p_strNewFormat Datos formatas į kurį reikia transformuoti.
*/
function g_str_fFormatDate(p_strDate, p_strOldFormat, p_strNewFormat)
{
    var objDate = g_obj_fGetDate(p_strDate, p_strOldFormat);
    return g_objDateTimeFormat.g_str_fFormat(objDate, p_strNewFormat);
}

/**
    Iš objektų(hashų) masyvo suformuoja hashą pagal vieną pasirinktą raktą. Hasho objektai yra masyvo
    numeriai.
    @author KM
    @version 1 2006.10.02
    @returns object[string] = index
*/
function g_hsh_fHashArrayByKey(p_arr_objInput, p_strKeyField)
{
    var hshReturn = new Object();
    if (p_arr_objInput == null) return hshReturn;
    for (var i = 0; i < p_arr_objInput.length; i++)
    {
        hshReturn[p_arr_objInput[i][p_strKeyField]] = i;
    }
    return hshReturn;    
}

/**
    Sujungia du hashus. Pirmą parametrą laiko defaultiniu, o ant jo viršaus užrašo antrąjį hashą.
    Kopijuojant daro kopijas taip, kad nepakeistų paduotų objektų.
    @param p_hshDefaults - hashas, ant kurio viršaus užrašoma.
    @param p_hshSpecificSettings - hashas, kurį užrašo ant viršaus.
    @author KM
    @version 1 2006-11-30
*/
function g_hsh_fMergeHashes(p_hshDefaults, p_hshSpecificSettings)
{
    var hshCopy = g_obj_fClone(p_hshDefaults);
    if (hshCopy == null)    // Jei defaultų nėra, tai tiesiog perkopijuojam antrą hashą
        return g_obj_fClone(p_hshSpecificSettings);
    for(var i in p_hshSpecificSettings)
		hshCopy[i] = g_obj_fClone(p_hshSpecificSettings[i]);
	return hshCopy;
}

/**
    Idėja tokia - padaryti universalų būdą iš XML eilutės gauti hash struktūrą. Transformacija atliekama
    taip - nuskaitomas tago pavadinimas ir pagal jį užhashuojama tėvo hashe. Jei elementas turi tekstinę reikšmę,
    tai ji išsaugoma elemente, kurio raktas yra '_val'. Jei xml elementas turi kelis vaikus su tuo pačiu 
    pavadinimu, tai šie vaikai dedami į masyvą.
    @author KM
*/
function g_hsh_fGetHashFromXml(p_strXml)
{
    var hshResult = new Object();
    var objDoc = getXml(p_strXml);  
    var mainNode = getChildren(objDoc)[0];      
    fParseXML(hshResult, mainNode);
    return hshResult;
}

/**
    Rekursinė funkcija, pereinanti XML medžio struktūrą.
*/
function fParseXML(p_hshParent, p_objNode)
{
    if (p_objNode.nodeType == 1)
    {
        var tagName = p_objNode.tagName;
        var hshPart = new Object();
        if (p_hshParent[tagName] == null)
        {
            p_hshParent[tagName] = hshPart;    
        }
        else
        if (ftypeof(p_hshParent[tagName]) == 'array')
        {
            p_hshParent[tagName].push(hshPart);            
        } 
        else
        {
            var objTemp = p_hshParent[tagName];
            p_hshParent[tagName] = new Array();
            p_hshParent[tagName].push(objTemp);
            p_hshParent[tagName].push(hshPart);
        }
        
        if (p_objNode.attributes)
        {
            for (i = 0; i < p_objNode.attributes.length; i++)
            {
                hshPart[p_objNode.attributes[i].nodeName] = p_objNode.attributes[i].nodeValue;
            }    
        }
        for (var i = 0; i < p_objNode.childNodes.length; i++)
        {
            fParseXML(hshPart, p_objNode.childNodes[i]);
        }
    }
    else if (p_objNode.nodeType == 3)
    {
        if (p_hshParent['_val'] == null) p_hshParent['_val'] = '';
        p_hshParent['_val'] += p_objNode.nodeValue;    
    }
}

/**
    Idėja tokia - padaryti universalų būdą iš XML eilutės gauti hash struktūrą.
    Antras idėjos įgyvendinimo variantas.
    @author KM
*/
function g_hsh_fGetHashFromXml2(p_strXml)
{
    var objDoc = getXml(p_strXml);  
    var mainNode = getChildren(objDoc)[0];      
    return obj_fParseXML2(mainNode);
}

/**
    Rekursinė funkcija, pereinanti XML medžio struktūrą.
    Neparsina atributų.
*/
function obj_fParseXML2(p_objNode)
{
    if (p_objNode.nodeType != 1) // Jei ne elementas tai vadinasi mums prieš tai jau reikėjo į suhandlinti
    {
        return p_objNode.nodeValue;
    }
    var objChildren = p_objNode.childNodes;
    if (objChildren.length == 0)
        return null;
    if (objChildren.length == 1 && objChildren[0].nodeType == 3)
    {
        return objChildren[0].nodeValue;
    }
    var hshResult = {};
    for (var i = 0, intLength = objChildren.length; i < intLength; i++)
    {
        if (objChildren[i].nodeType == 1)
        {
            var strTagName = objChildren[i].tagName;
            if (hshResult[strTagName] == null)
            {
                hshResult[strTagName] = obj_fParseXML2(objChildren[i]);
            }
            else if (ftypeof(hshResult[strTagName]) == 'array')
            {
                hshResult[strTagName].push(obj_fParseXML2(objChildren[i]));
            }
            else
            {
                var objTemp = hshResult[strTagName];
                hshResult[strTagName] = [];
                hshResult[strTagName].push(objTemp);
                hshResult[strTagName].push(obj_fParseXML2(objChildren[i]));    
            }
            
        }
    }
    return hshResult;
}

/**
    Gauna hashą ir jį sutvarko, kad gautųsi tvarkingas hashų masyvas.
*/
function g_hsh_fGetFixedHashFromXml(p_strResults)
{
    var hshResults = g_hsh_fGetHashFromXml2(p_strResults);
    if (hshResults == null)
        hshResults = {'Table': []};    
    if (hshResults['Table'] == null)
        hshResults['Table'] = [];   
    if (!g_bln_fIsArray(hshResults['Table']))
        hshResults['Table'] = [hshResults['Table']];
    return hshResults;
}
/**
    Objektą užkoduoja xml stringu.
*/
function g_str_fGetXmlFromObject(p_objObject, p_strKey, p_intLevel)
{
    if (p_intLevel <= 0)
        return '';
    if (p_strKey == null || p_strKey == '')
    {
        p_strKey = 'root';
    }
    var strReturn = '<' + g_str_fClearXmlEntities('' + p_strKey) + '>';
    if(typeof(p_objObject) == 'object' && p_objObject != null) 
    {
        if (p_objObject.constructor == Array)
        {
            for(var intKey in p_objObject)
            {
                if (g_bln_fIsInt(intKey) && typeof (p_objObject[intKey]) != 'undefined')
                {
                    strReturn += g_str_fGetXmlFromObject(p_objObject[intKey], intKey, p_intLevel - 1);
                }
            }
        }
        else
        if (p_objObject.constructor == Object || p_objObject.constructor.toString().match(/\s*function (.*)\(/))
        {
            for(strKey in p_objObject)
            {
                strReturn += g_str_fGetXmlFromObject(p_objObject[strKey], strKey, p_intLevel - 1);
            }
        }
        else
            strReturn += g_str_fEscapeXmlEntities('' + p_objObject);
    }
    else 
    {
        if (p_objObject != null)
        {
            strReturn += g_str_fEscapeXmlEntities('' + p_objObject);
        }
    }
    strReturn += '</' + g_str_fClearXmlEntities('' + p_strKey) + '>';
    return strReturn;
}

function g_str_fEscapeXmlEntities(p_strXmlString)
{
    if (!p_strXmlString) return '';        
    return p_strXmlString.replace(/&/g, '&amp;').replace(/\'/g, '&apos;').replace(/\"/g, '&quot;').replace(/>/g, '&gt;').replace(/</g, '&lt;');
}

function g_str_fClearXmlEntities(p_strXmlString)
{
    if (!p_strXmlString) return '';
    return p_strXmlString.replace(/[\'\"&><]/gi, '');
}   

/**
    Priskiria nurodytas stiliaus savybes nurodytam DOM elementui.
    @param p_objDOMElement - DOM elementas, turi turėti style objektą;
    @param p_objStyle - Dirbtinis stiliaus objektas su nurodytomis savybėmis, kurias reikia perrašyti;
*/
function g_fApplyStyleProperties(p_objDOMElement, p_objStyle)
{
    if (!p_objDOMElement || !p_objDOMElement.style || !p_objStyle)
        return;
    var objElementStyle = p_objDOMElement.style;
    for (var key in p_objStyle)
    {
        objElementStyle[key] = p_objStyle[key];
    }    
} 

/**  
    KM 2006-07-31 Užkoduoja dvimatį stringų masyvą siuntimui į URL.
    Skyrikliai paimami iš konstantų cSYS.cDELIM1 ir cSYS.cDELIM2.
*/
function g_str_fEncodeArray(p_arr_arr_strInput)
{
    var strReturn = '';
    for (var i = 0; i < p_arr_arr_strInput.length; i++)
    {
        for (var j = 0; j < p_arr_arr_strInput[i].length; j++)
        {
            strReturn += encode(p_arr_arr_strInput[i][j]);
            if (j != p_arr_arr_strInput[i].length - 1)
            {
                strReturn += encode(cSYS.cDELIM2);    
            }    
        }
        if (i != p_arr_arr_strInput.length - 1)
        {
            strReturn += encode(cSYS.cDELIM1);    
        }
    }    
    return strReturn;
}

/**
    Iš hashų masyvo elementų išrenka tik tam tikrą lauką ir jį įrašo į naują masyvą.
    @param p_arr_hshInput {hash[]} Hashų masyvas.
    @param p_strKey {string} Išsirinktas laukas.
    @returns Eilučių masyvą.
    @type string[]
*/
function g_arr_str_fGetListing(p_arr_hshInput, p_strKey)
{
    if (p_strKey == null)
        return g_obj_fClone(p_arr_hshInput);
    if (p_arr_hshInput == null)
        return p_arr_hshInput;
    var arr_strResult = new Array();
    var intLength = p_arr_hshInput.length;
    for (var i = 0; i < intLength; i++)
    {
        arr_strResult.push(p_arr_hshInput[i][p_strKey]);
    }   
    return arr_strResult;
}

//---------------------------------------------------------------
/** 
    Masyve ieško duotos reikšmės, jei randa grąžina jos eilės numerį , jei ne -1
*/
Array.prototype.inArray = function (value)
{
	for (var i = 0; i < this.length; i++) 
	{
		if (this[i] == value) 
		{
			return i;
		}
	}
	return -1;
};
//---------------------------------------------------------------

/**
    Patikrina ar masyvas turi paduotą elementą.
    @memberOf Array
    @scope Array.prototype
*/
Array.prototype.contains = function(r)  { 
  for(var x=0;x<this.length;x++)  { 
    if(this[x]==r)  { 
      return true; 
    }}  return false; 
} 
//---------------------------------------------------------------

/**
    @memberOf Array
    @scope Array.prototype
*/
Array.prototype.intersection = function(arr2)  
{ 
  var returnArray = new Array(); var y = 0; 
  for(var x=0;x<this.length;x++)  
  { 
    if(arr2.contains(this[x]))  
    { 
      returnArray[y++] = this[x]; 
    }
  }  
  return y==0?null:returnArray; 
} 

/**
 * isSimilar - Returns true for similar arrays, type-insensitive
 * 
 * @example
 *  [1].isSimilar(['1']) == true
 *  [1, 2].isSimilar([1, false]) == false
 *  
 * @return	{Boolean}
 * @param	{Object} Array
    @memberOf Array
 */
Array.prototype.isSimilar = function(array) 
{
    return (this.toString() == array.toString());
}

/**
 * complement - Fills up empty array values from another array, length is the same
 * 
 * @example
 *  [1, null].complement([3, 4]) == [1, 4]
 *	[undefined, '1'].complement([2, 3, 4]) == [2, '1']

 * @return	{Array} this
 * @param	{Object} Array
    @memberOf Array
 */
Array.prototype.complement = function(array) 
{
	for (var i = 0, j = this.length; i < j; i++)
	{ 
	    if (this[i] == null)
	        this[i] = array[i];
	}
	return this;
}
//---------------------------------------------------------------
//------------------BEGIN prototype sort @@@@@@@@@@@@@@@@@@@@@@@@
//---------------------------------------------------------------
/**
    @memberOf Array
*/
Array.prototype.swap = function(a, b)
{
	var tmp=this[a];
	this[a]=this[b];
	this[b]=tmp;
}
//---------------------------------------------------------------
if(cFF)
{
    Array.prototype.sort = function(func)
    {
        return msort(this, 0, this.length, func);
    }
}
//---------------------------------------------------------------
function insert(array, begin, end, v, func)
{
	while((begin + 1 < end) && (func(array[begin+1], v) < 0)) 
	{
		array.swap(begin, begin+1);
		++begin;
	}
	array[begin] = v;
}
//---------------------------------------------------------------
function merge(array, begin, begin_right, end, func)
{
	for(;begin < begin_right; ++begin) 
	{
		if(func(array[begin], array[begin_right]) > 0) 
		{
			var v = array[begin];
			array[begin] = array[begin_right];
			insert(array, begin_right, end, v, func);
		}
	}
}
//---------------------------------------------------------------
function msort(array, begin, end, func)
{
	var size = end - begin;
	if(size < 2) return;

	var begin_right = begin + Math.floor(size/2);

	msort(array, begin, begin_right, func);
	msort(array, begin_right, end, func);
	merge(array, begin, begin_right, end, func);
	return array;
}
//---------------------------------------------------------------
//------------------END prototype sort @@@@@@@@@@@@@@@@@@@@@@@@@@
//---------------------------------------------------------------

function g_bln_fIsArray(p_objObject)
{
    if (p_objObject == null)
        return false;
    if (p_objObject.constructor == Array)
        return true;
    return false;
}

//////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////          Pirmas variantas            ///////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////

/**
    Hashuota pagal raktą ir indeksuota pagal numerį struktūra.     
    Geriausiai (greičiausiai) veikia kai įterpinėjama į galą ir išmetinėjama iš galo, 
    t.y. kai veikia kaip stekas.
*/
function clsIndexedHash()
{
    this.hsh_intIndexHash = {};
    this.arr_objArray = [];
}

    /**
        Prideda vieną objektą pagal raktą ir indeksą, atnaujina visus indeksus.
        @param p_objElement - įterpiamas elementas;
        @param p_intIndex - indeksas, parodantis į kurią masyvo vietą reikia įterpti;
        @param p_strKey - indeksas į kurio vietą reikia įterpti.
    */    
    clsIndexedHash.prototype.g_str_fAdd = function(p_objElement, p_intIndex, p_strKey)
    {
        if (!p_objElement)    
            return;
        // Įterpiam pagal indexą
        if (p_intIndex < 0)
        {
            p_intIndex = 0;    
        }
        else
        if (p_intIndex == null || p_intIndex >= this.arr_objArray.length)
        {
            p_intIndex = this.arr_objArray.length;   
        }   
        
        this.arr_objArray.splice(p_intIndex, 0, p_objElement); 
        for (var i = p_intIndex + 1, intLength = this.arr_objArray.length; i < intLength; i++)
        {
            this.hsh_intIndexHash[this.arr_objArray[i].__key] = i;    
        }
        
        // Įterpiam pagal raktą
        var strKey = p_strKey || g_str_fIdGenerator();
        while(this.g_fKeyExists(strKey))   // Jeigu toks raktas egzistuoja, tol generuojam naują raktą
        {
            strKey = g_str_fIdGenerator();
        } 
        this.hsh_intIndexHash[strKey] = p_intIndex;
        p_objElement.__key = strKey;
        return strKey;
    }

    /**
        Gaunamas elementas pagal indeksą.
    */    
    clsIndexedHash.prototype.g_fUninit = function()
    {
        delete this.hsh_intIndexHash;
        delete this.arr_objArray;    
        this.hsh_intIndexHash = {};
        this.arr_objArray = [];  
    }

    /**
        Gaunamas elementas pagal indeksą.
    */    
    clsIndexedHash.prototype.g_obj_fGetAllElements = function()
    {
        return [].concat(this.arr_objArray);        
    }
    
    /**
        Gaunamas elementas pagal indeksą.
    */    
    clsIndexedHash.prototype.g_obj_fGetByIndex = function(p_intIndex)
    {
        return this.arr_objArray[p_intIndex];        
    }
        
    /**
        Gaunamas elementas pagal raktą.
    */    
    clsIndexedHash.prototype.g_obj_fGetByKey = function(p_strKey)
    {
        var intIndex = this.hsh_intIndexHash[p_strKey];
        if (intIndex == null)
            return null;
        return this.arr_objArray[intIndex];      
    }

    
    /**
        Gauna elementų skaičių hashe;
    */    
    clsIndexedHash.prototype.g_int_fGetCount = function()
    {
        return this.arr_objArray.length;
    } 
    
    /**
        Gauna pirmą elementą.    
    */
    clsIndexedHash.prototype.g_obj_fGetFirst = function()
    {
        return this.arr_objArray[0];        
    }


    /**
        Gaunamas elemento indeksas iš elemento.
    */    
    clsIndexedHash.prototype.g_obj_fGetIndex = function(p_objElement)
    {
        return this.hsh_intIndexHash[p_objElement.__key];        
    }

    /**
        Gaunamas elemento indeksas pagal raktą.
    */    
    clsIndexedHash.prototype.g_obj_fGetIndexFromKey = function(p_strKey)
    {
        return this.hsh_intIndexHash[p_strKey];        
    }

    /**
        Gauna elemento raktą.    
    */
    clsIndexedHash.prototype.g_str_fGetKey = function(p_objElement)
    {
        var strKey = p_objElement.__key;
        if (this.g_fIsIn(strKey))
            return strKey;
        return null;        
    }

    /**
        Gauna paskutinį elementą.    
    */
    clsIndexedHash.prototype.g_obj_fGetLast = function()
    {
        var intLength = this.arr_objArray.length;
        if (intLength > 0)        
        {
            return this.arr_objArray[intLength - 1];    
        }
        return null;
    }  
    
    /**
        Gauna sekantį elementą, po nurodyto elemento.
    */
    clsIndexedHash.prototype.g_obj_fGetNext = function(p_objElement)
    {  
        var intIndex = this.hsh_intIndexHash[p_objElement.__key];
        if (intIndex == null)
            return null;
        return this.arr_objArray[intIndex + 1];         
    } 
    
    /**
        Gauna elementą esantį prieš nurodytą elementą.
    */
    clsIndexedHash.prototype.g_obj_fGetPrevious = function(p_objElement)
    {
        var intIndex = this.hsh_intIndexHash[p_objElement.__key];
        if (intIndex == null || intIndex == 0)
            return null;
        return this.arr_objArray[intIndex - 1];          
    }

    /**
        Prideda vieną objektą po nurodyto objekto.
        @param p_objElement - įterpiamas elementas;
        @param p_objReferenceElement - elementas, po kurio įterpiama;
        @param p_strKey - indeksas į kurio vietą reikia įterpti.
    */    
    clsIndexedHash.prototype.g_str_fInsertAfter = function(p_objElement, p_objReferenceElement, p_strKey)
    {
        var intIndex = this.hsh_intIndexHash[p_objReferenceElement.__key] + 1;
        return this.g_str_fAdd(p_objElement, intIndex, p_strKey);                
    }
    
   
    /**
        Prideda vieną objektą prieš nurodytą objektą.
        @param p_objElement - įterpiamas elementas;
        @param p_intIndex - elementas, prieš kurį įterpiama;
        @param p_strKey - indeksas į kurio vietą reikia įterpti.
    */    
    clsIndexedHash.prototype.g_str_fInsertBefore = function(p_objElement, p_objReferenceElement, p_strKey)
    {
        var intIndex = this.hsh_intIndexHash[p_objReferenceElement.__key];
        return this.g_str_fAdd(p_objElement, intIndex, p_strKey);    
    }
    
    /**
        Gauna elementą esantį prieš nurodytą elementą.
    */
    clsIndexedHash.prototype.g_bln_fIsFirst = function(p_objElement)
    {
        return this.arr_objArray[0] == p_objElement;         
    }
    
    /**
        Prideda vieną objektą prieš nurodytą objektą.
        @param p_objElement - įterpiamas elementas;
        @param p_intIndex - indeksas, parodantis į kurią masyvo vietą reikia įterpti;
        @param p_strKey - indeksas į kurio vietą reikia įterpti.
    */    
    clsIndexedHash.prototype.g_fIsIn = function(p_objElement)
    {
        return this.hsh_intIndexHash[p_objElement.__key] != null;      
    }  
    
    /**
        Gauna elementą esantį prieš nurodytą elementą.
    */
    clsIndexedHash.prototype.g_bln_fIsLast = function(p_objElement)
    {
        return this.arr_objArray[this.arr_objArray.length - 1] == p_objElement;          
    }
    
    /**
        Su visais elementais iteruoja per nurodytą funkciją.
    */    
    clsIndexedHash.prototype.g_fIterate = function(p_fFunction)
    {      
        for (var i = 0, intLength = this.arr_objArray.length; i < intLength; i++)
        {
            p_fFunction(this.arr_objArray[i]);    
        }
    }

    /**
        Su visais elementais iteruoja per nurodytą funkciją su kontekstu.
    */    
    clsIndexedHash.prototype.g_fIterateWithContext = function(p_objContext, p_fFunction)
    {
        for (var i = 0, intLength = this.arr_objArray.length; i < intLength; i++)
        {
            p_fFunction.apply(p_objContext, this.arr_objArray[i]);      
        }    
    } 

    /**
        Patikrina ar egzistuoja toks raktas.
        @param p_objElement - įterpiamas elementas;
        @param p_intIndex - indeksas, parodantis į kurią masyvo vietą reikia įterpti;
        @param p_strKey - indeksas į kurio vietą reikia įterpti.
    */    
    clsIndexedHash.prototype.g_fKeyExists = function(p_strKey)
    {
        return this.hsh_intIndexHash[p_strKey] != null; // paverčiam į bool
    }
    
    /**
        Išmeta ir grąžina vieną elementą iš galo.
        @return paskutinį elementą.
    */    
    clsIndexedHash.prototype.g_obj_fPop = function()
    {
        return this.g_obj_fRemoveByIndex(this.arr_objArray.length - 1);               
    }

    /**
        Prideda vieną elementą į galą.
        @param p_objElement - įterpiamas elementas;
        @param p_strKey - raktas, pagal kurį bus norima gauti elementą.
    */    
    clsIndexedHash.prototype.g_str_fPush = function(p_objElement, p_strKey)
    {
        return this.g_str_fAdd(p_objElement, this.arr_objArray.length, p_strKey);                
    }

    /**
        Išmeta vieną objektą pagal objektą.
    */    
    clsIndexedHash.prototype.g_obj_fRemove = function(p_objElement)
    {       
        return this.g_obj_fRemoveByKey(p_objElement.__key);  
    }  

    /**
        Išmeta vieną objektą pagal raktą.
    */    
    clsIndexedHash.prototype.g_obj_fRemoveByIndex = function(p_intIndex)
    {       
        if (p_intIndex < 0 || p_intIndex == null || p_intIndex >= this.arr_objArray.length)
        {
            return null;   
        }   
        
        var objRemoved = this.arr_objArray[p_intIndex];
        delete this.hsh_intIndexHash[objRemoved.__key];
        objRemoved.__key = null;
        this.arr_objArray.splice(p_intIndex, 1); 
        for (var i = p_intIndex, intLength = this.arr_objArray.length; i < intLength; i++)
        {
            this.hsh_intIndexHash[this.arr_objArray[i].__key] = i;    
        } 
        return objRemoved;     
    }   
    
    /**
        Išmeta vieną objektą pagal raktą.
    */    
    clsIndexedHash.prototype.g_obj_fRemoveByKey = function(p_strKey)
    {
        var intIndex = this.hsh_intIndexHash[p_strKey];
        if (intIndex == null)
            return null;
        return this.g_obj_fRemoveByIndex(intIndex);
    }
    
    clsIndexedHash.prototype.g_fReplace = function(p_objOldItem, p_objNewItem, p_strKeyIfNew)
    {
        if (p_objOldItem == null || this.hsh_intIndexHash[p_objOldItem.__key] == null) // jei senas neegzistuoja
        {
            this.g_str_fAdd(p_objNewItem, this.arr_objArray.length, p_strKeyIfNew);
        }
        else // senas egzistuoja
        {
            p_objNewItem.__key = p_objOldItem.__key;
            var intIndex = this.hsh_intIndexHash[p_objOldItem.__key];
            this.arr_objArray.splice(intIndex, 1, p_objNewItem);
        }
    }
    
/**
    Užpildo paduotą hashą paieškos duomenimis.
    @param p_hshParamHash Paieškos parametrų hashas;
    @param p_strKey Naujo parametro pavadinimas;
    @param p_strValue Naujo parametro reikšmė;
    @param p_strFunction Parametrą atitinkanti funkcija;
*/
function g_fFillHash(p_hshParamHash, p_strKey, p_strValue, p_strFunction)
{
    if (p_strValue)
    {
        p_hshParamHash[p_strKey] = p_strValue;
        if (p_strFunction)
            p_hshParamHash[p_strKey + 'Fun'] = p_strFunction;
    }
}

// Įvairių duomenų struktūrų funkcijos \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

//<><><>////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////                                                 ///////////////
////////////////         Pozicijos nustatymo funkcijos           ///////////////
////////////////                                                 ///////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

function ekranoWH() // Grazina einamojo lango/dialogo ploti ir auksti masyvu
{
	var winW = null;
	var winH = null;
	if (navigator.appName=="Netscape") 
	{
		winW = window.innerWidth;
		winH = window.innerHeight;
	}
	else	
	if (navigator.appName.indexOf("Microsoft")!=-1) 
	{
		winW = document.body.offsetWidth;
		winH = document.body.offsetHeight;
	}
	return([winW,winH]);
}
//----------------------------------------------------------
/* gra?ina lango auk?ti */
function g_fGetViewportHeight() 
{
// 2006 12 28 RG window.innerHeight ant FF netinka nes yskaiciuoja horizontalu scroll http://developer.mozilla.org/en/docs/DOM:window#Properties
	//if(window.innerHeight != window.undefined) { return window.innerHeight;}
	if(document.compatMode == 'CSS1Compat') { return document.documentElement.clientHeight;}
	if(document.body) {return document.body.clientHeight; }
	return window.undefined; 
}
//----------------------------------------------------------
/* gra?ina lango ploti , mozilai del scrollbaru ploti padidina 16px */
function g_fGetViewportWidth() 
{
	var intW = window.undefined;
	if( window.innerWidth != window.undefined) intW = parseInt(window.innerWidth); 
	if( document.compatMode == 'CSS1Compat') intW = parseInt(document.documentElement.clientWidth); 
	if( document.body) intW = parseInt(document.body.clientWidth);
	//if( cFF ) intW += 16; 
	return intW;
}

/**
    Grąžina lango vertikalų skrolinimą.     
*/
function g_int_fGetWindowScrollTop()
{
    if( document.compatMode == 'CSS1Compat') 
        return document.documentElement.scrollTop; 
    else
        return document.body.scrollTop;    
}
//------------------------------------------------------------

/**
    Grąžina lango horizontalų skrolinimą.
*/
function g_int_fGetWindowScrollLeft()
{
    if( document.compatMode == 'CSS1Compat') 
        return document.documentElement.scrollLeft; 
    else
        return document.body.scrollLeft;    
}
//------------------------------------------------------------

//---------------------------------------------------------------
/* gra?ina einamojo lango centro koordinates ( iskaitant scrollinima )*/
function g_arr_fCentroKoordinates()
{
	var intWindowHeight = g_fGetViewportHeight();
	var intWindowWidth = g_fGetViewportWidth();
	var objBody = document.body;	
	var intScrollTop = parseInt(objBody.scrollTop,10);
	var intScrollLeft = parseInt(objBody.scrollLeft,10);		
	var intY = (intScrollTop + (intWindowHeight / 2));
	var intX = (intScrollLeft + (intWindowWidth / 2));
	return([intX, intY]);
}
//---------------------------------------------------------------
/* paduota objekta pozicionuoja einamo lango viduryje */
function g_fCentruoti(p_objLangas)
{
	var int_arrCoord = g_arr_fCentroKoordinates();
	p_objLangas.style.top =  (int_arrCoord[1] - parseInt(p_objLangas.offsetHeight) / 2) + "px";
	p_objLangas.style.left = (int_arrCoord[0] - parseInt(p_objLangas.offsetWidth) / 2) + "px";
}
//---------------------------------------------------------------
/** 
    grazina ar duotas taskas yra ekrane
    RG 2006 11 16 updated 
    RG 2006 12 29 updated 
*/
function g_bln_fIsOnScreen(pX,pY,p_strBoundaryObjId)
{
	var objBody = document.body;	
	var intScrollTop = 0;
	var intScrollLeft = 0; 
 // IE6 +4.01 
    if (document.documentElement)
    {
        if(document.documentElement.scrollTop)
        {
            intScrollTop = document.documentElement.scrollTop;
        }
        if(document.documentElement.scrollLeft)
        {
            intScrollLeft = document.documentElement.scrollLeft;
        }
    }
 // IE5 or DTD 3.2
   // else 
    
    if (document.body)
    {
        if(document.body.scrollTop)
        {
            intScrollTop = document.body.scrollTop;
        }
        if(document.body.scrollLeft)
        {
            intScrollLeft = document.body.scrollLeft;
        }
    }
	
	var blnIsOnScreen = false;
	if(pX >= intScrollLeft && pX < (intScrollLeft + g_fGetViewportWidth()) )
	{
		if(pY >= intScrollTop && pY < (intScrollTop + g_fGetViewportHeight()) )
		{
			blnIsOnScreen = true;
		}
	}
	if(blnIsOnScreen == true)
	{
     // jei duotas elementas kuriame turi buti taškas   
        if(p_strBoundaryObjId != null)
        {
            var objBoundaryObj = document.getElementById(p_strBoundaryObjId);
            if(objBoundaryObj == null) {consoleA('boundary obj doesnt exist');return false;}
            var arr_intBoundaryPos = objPosition(objBoundaryObj);
            var intX = arr_intBoundaryPos[2];
            var intY = arr_intBoundaryPos[3];
            var intWidth = arr_intBoundaryPos[0];
            var intHeight = arr_intBoundaryPos[1];
            if(pX > intX && pX < (intX + intWidth))
	        {
		        if(pY > intY && pY < (intY + intHeight) )
		        {
			        return (true);
		        }
	        }
	        return (false);
        }	  
        else
            return (true);  
	}
	else
	    return (false);
}
//---------------------------------------------------------------
/* 
    @id - galima paduoti objekto Id arba pati objekta
    @p_strType - objekto pozicijos skaiciavimo budas
	    jei 'simple' tiesiog gra?ina .left ir .top
	    jei nenurodytas tai skaiciuoja tiksliai puslapio at?vilgiu.
    Gra?ina objekto ploti, auk?ti, x koordinate, y koordinate.
*/
function objPosition(id, p_strType)
{
	var obj = null;
	try
	{
		if(typeof(id) != 'object')
		{
			obj = document.getElementById(id);	
		}
		else
		{
			obj = id;	
		}
		var l=0; var t=0; var w=0; var h=0;
		w = obj.offsetWidth;
		h = obj.offsetHeight;
	}
	catch(strError)
	{
		return;
	}
	if(p_strType == null || p_strType != 'simple')
	{
		if (obj.offsetParent)
		{
			for (posX = 0, posY = 0; obj.offsetParent; obj = obj.offsetParent)
			{
				if (obj.id == 'minwidthcont' || obj.className == 'minwidthcont') // Padaryta tam, kad ant IE panaudotas minWidth mechanizmas neišdarkytų pozicijos. Objektas, kurio klasė yra minwidthcont turi offsetLeft lygų -[min_width] (pvz.: -800), taigi į jį reikia neatsižvelgti.
			        continue;
				posX += obj.offsetLeft;
				posY += obj.offsetTop;
			}
			l = posX; t = posY;
		}
		else if(obj.x)
		{
			l = obj.x; t = obj.y;
		}
	}
	else 
		if(p_strType == 'simple')
		{  
			var tempLeft = obj.style.left;
			var tempTop = obj.style.top;			
			l = parseInt(tempLeft);
			t = parseInt(tempTop);
		}
	return([w,h,l,t]);
}

/* Grąžina pelės koordinates puslapyje ( įskaitant ir pascrollinimus ) */
function getMouse(e)
{
	var xPos;
	var yPos;		
	if (e.pageX || e.pageY)
	{
		xPos = e.pageX;
		yPos = e.pageY;
	}
	else if (e.clientX || e.clientY)
	{
		xPos = e.clientX + document.body.scrollLeft;
		yPos = e.clientY + document.body.scrollTop;
	}
	if (cIE) // KM 2007.09.10
	{
	    yPos += g_int_fGetWindowScrollTop();
	}
	return([xPos,yPos]);
}

function g_obj_fGetMousePoint(e)
{
    return new clsPoint(getMouse(e));
}

/**
    Meniu vietos nustatymas pagal pelę.
*/    
function clsMouseAligning()
{
    //this.objAnchor = p_objAnchor;
}

    /**
        Suranda poziciją pagal pelės meniu atsiradimo algoritmą.
        @param p_objEvent Pelės paspaudimo įvykis.
        @param p_intWidth Atsirandančio meniu plotis.
        @param p_intHeight Atsirandančio meniu aukštis.
    */
    clsMouseAligning.prototype.g_obj_fGetPosition = function(p_objEvent, p_intWidth, p_intHeight)
    {
        if (p_intWidth < 0)
            p_intWidth = 0;
        if (p_intHeight < 0)
            p_intHeight = 0;   
        
        //var objAnchorRegion = g_obj_fGetRegion(this.objAnchor);
        var objPoint = g_obj_fGetMousePoint(p_objEvent); 
        var objAnchorRegion = new clsRegion(objPoint.X, objPoint.Y, 0, 0);
        var objRegion = g_obj_fGetSuitableRegion(objAnchorRegion, p_intWidth, p_intHeight);
        //var objLocalCoords = g_obj_fMakeRelative(objRegion, objParent);
        return objRegion;             
    }

/**
    Meniu vietos nustatymas pagal bazinį elementą.    
    @param p_objAnchor Paduodamas HTML elementas, pagal jį atsiranda meniu.    
*/    
function clsAnchorAligning(p_objAnchor)
{
    this.objAnchor = p_objAnchor;    
}
    /**
        Suranda poziciją pagal šalia atraminio elemento iššokstančio meniu atsiradimo algoritmą.
        @param p_objEvent Įvykis, jis reikalingas tik dėl interfeiso.
        @param p_intWidth Atsirandančio meniu plotis.
        @param p_intHeight Atsirandančio meniu aukštis.
    */
    clsAnchorAligning.prototype.g_obj_fGetPosition = function(p_objEvent, p_intWidth, p_intHeight)
    {
        if (p_intWidth < 0)
            p_intWidth = 0;
        if (p_intHeight < 0)
            p_intHeight = 0;   
        var objAnchorRegion = g_obj_fGetRegion(this.objAnchor);
        var objRegion = g_obj_fGetSuitableRegion(objAnchorRegion, p_intWidth, p_intHeight);
        return objRegion;            
    }    

/**
    Gauna regioną, kuris tinka atvaizdavimui. Pirma pasižiūri ar vaizduojamas objektas
    tilps į kurį nors iš keturių galimų puslapio regionų, o paskui iškviečia funkciją 
    g_obj_fGetSuitablePosition, kuri suranda tikslią vietą.
    @param p_objAnchorRegion Elemento, apie kurį turi atsirasti meniu regiono objektas.
    @param p_intWidth Iššokstančio meniu plotis.
    @param p_intHeight Iššokstančio meniu aukštis.
    @returns Iššokstančio meniu regionas - kairiojo viršutinio kampo koordinatės ir plotis bei aukštis.
*/
function g_obj_fGetSuitableRegion(p_objAnchorRegion, p_intWidth, p_intHeight)
{
    var intWindX1 = g_int_fGetWindowScrollLeft();
    var intWindW = g_fGetViewportWidth();
    var intWindX2 = intWindX1 + intWindW;
    var intWindY1 = g_int_fGetWindowScrollTop();
    var intWindH = g_fGetViewportHeight();
    var intWindY2 = intWindY1 + intWindH;
    var intY1 = p_objAnchorRegion.Y;
    var intY2 = p_objAnchorRegion.Y + p_objAnchorRegion.H;
    var intX1 = p_objAnchorRegion.X;
    var intX2 = p_objAnchorRegion.X + p_objAnchorRegion.W;
        
    // Tikrinimas pagal regionus, reikia maximizuoti aukštį
    // Regionas po meniu iškvietėju
    var intDownY = intWindY2 - intY2;
    // Regionas virš meniu iškvietėjo
    var intUpY = intY1 - intWindY1;
    // Regionas iškvietėjo dešinėje
    var intRightX = intWindX2 - intX2;
    // Regionas iškvietėjo kairėje
    var intLeftX = intX1 - intWindX1;
    
    // Tikriname ar tilps  pilnai
    if (p_intWidth < intWindW && (intDownY > 0 && p_intHeight < intDownY ||     // Tilps apačioje
        intUpY > 0 && p_intHeight < intUpY) ||                                  // Tilps viršuje
        p_intHeight < intWindH && (intRightX > 0 && p_intWidth < intRightX ||   // Tilps dešinėje
        intLeftX > 0 && p_intWidth < intLeftX))                                 // Tilps kairėje
    {
        return g_obj_fGetSuitablePosition(p_objAnchorRegion, p_intWidth, p_intHeight);
    }
         
    // Jei iki čia atėjo tai niekur pilnai netelpa
    // Ieškosim pagal tai kurioje vietoje esanti meniu ir regiono sankirta turėtų didžiausią plotą
    var intMaxWidth = 0;
    var intMaxHeight = 0;
    
    var intBiggerHeight = Math.max(intDownY, intUpY);
    var intCurWidth = Math.min(p_intWidth, intWindW);
    var intCurHeight = Math.min(p_intHeight, intBiggerHeight);
    if (intCurWidth * intCurHeight > intMaxWidth * intMaxHeight)
    {
        intMaxWidth = intCurWidth;
        intMaxHeight = intCurHeight;
    }
        
    var intBiggerWidth = Math.max(intRightX, intLeftX);
    var intCurWidth = Math.min(p_intWidth, intBiggerWidth);
    var intCurHeight = Math.min(p_intHeight, intWindH);
    if (intCurWidth * intCurHeight > intMaxWidth * intMaxHeight)
    {
        intMaxWidth = intCurWidth;
        intMaxHeight = intCurHeight;
    }
       
    return g_obj_fGetSuitablePosition(p_objAnchorRegion, intMaxWidth, intMaxHeight);
}

/**
    Gauna regioną, kuris tinka meniu atvaizdavimui.
    @param p_objAnchorRegion Elemento, apie kurį turi atsirasti meniu regiono objektas.
    @param p_intWidth Iššokstančio meniu plotis.
    @param p_intHeight Iššokstančio meniu aukštis.
    @returns Iššokstančio meniu regionas - kairiojo viršutinio kampo koordinatės ir plotis bei aukštis.
    Lango regionas          
    .-------------------------------------.WindY1
    |    Anchor regionas                  |
    |            .-----------.Y1          |
    |            |           |            |
    |            |           |            |WindH
    |            .___________.Y2          |          
    |            X1          X2           |
    |                                     |
    |                                     |
    ._____________________________________.WindY2          
    WindX1          intWindW              WindX2
    
    Tikrinimas ar viskas gerai remiasi blnXXOK kintamaisiais 
    (kur pirmas X - W arba H, o antras X - kintamojo numeris),
     kurie nurodo ar atitinkama meniu pločio ar aukščio pozicija
    yra gera. 
    
    Plotis:
            |   Anchor regionas    |
            .______________________.
    
            |---------------------------------------- W1
       ----------------------------|                  W2
          |---------------------------|               W3
                                   |--------          W4
     -------|                                         W5                                
                        |-----------------------      W6  
       ---------------------|                         W7
    
    Pavyzdžiui blnW1OK == true reiškia, kad galima kurti meniu nuo kairiojo anchor regiono krašto į dešinę.
    
    Aukštis:
    
         H2   H7
         | H4 |
         | |H5|
         | |- |
    --.  --|| |
      |   ||| |
    A |   ||| |
    n |   ||| |
    c |   ||| |
    h |   |||-|
    o |   ||||-
    r |   ||||
      |   ||||
      |   ||||
      |   ||||
    __. - |-||
        | | -|
        | |  |
        | H3 | 
        |    |
        |    H6
        |
        H1

*/
function g_obj_fGetSuitablePosition(p_objAnchorRegion, p_intWidth, p_intHeight)
{
    var intWindX1 = g_int_fGetWindowScrollLeft();
    var intWindW = g_fGetViewportWidth();
    var intWindX2 = intWindX1 + intWindW;
    var intWindY1 = g_int_fGetWindowScrollTop();
    var intWindH = g_fGetViewportHeight();
    var intWindY2 = intWindY1 + intWindH;
    
    var intY1 = p_objAnchorRegion.Y;
    var intY2 = p_objAnchorRegion.Y + p_objAnchorRegion.H;
    var intX1 = p_objAnchorRegion.X;
    var intX2 = p_objAnchorRegion.X + p_objAnchorRegion.W;
    
    var blnH1OK = g_bln_fFitsInRange(intWindY1, intWindY2, intY2, intY2 + p_intHeight); // Aukštis žemiau anchoro
    var blnW1OK = g_bln_fFitsInRange(intWindX1, intWindX2, intX1, intX1 + p_intWidth); // Plotis nuo kairiojo šono į dešinę
    
    if (blnW1OK && blnH1OK)
        return new clsRegion(intX1, intY2, p_intWidth, p_intHeight);//1
    
    var blnW2OK = g_bln_fFitsInRange(intWindX1, intWindX2, intX2 - p_intWidth, intX2); // Plotis nuo dešiniojo šono į kairę
    if (blnW2OK && blnH1OK)
        return new clsRegion(intX2 - p_intWidth, intY2, p_intWidth, p_intHeight);//2
    
    var blnW6OK = g_bln_fFitsInRange(intWindX1, intWindX2, intWindX1, intWindX1 + p_intWidth); // Plotis nuo lango kairiojo šono į dešinę
    blnW3OK = blnW6OK && g_bln_fFitsInRange(intWindX1, intWindX1 + p_intWidth, intX1, intX2); // Jis turi pilnai liesti anchoro apačią arba viršų
    if (blnW3OK && blnH1OK)
        return new clsRegion(0, intY2, p_intWidth, p_intHeight);//3    
    
    var blnH2OK = g_bln_fFitsInRange(intWindY1, intWindY2, intY1 - p_intHeight, intY1); // Aukštis aukščiau anchoro
    
    if (blnW1OK && blnH2OK)
        return new clsRegion(intX1, intY1 - p_intHeight, p_intWidth, p_intHeight);//4
    
    if (blnW2OK && blnH2OK)
        return new clsRegion(intX2 - p_intWidth, intY1 - p_intHeight, p_intWidth, p_intHeight);//5
    
    if (blnW3OK && blnH2OK)
        return new clsRegion(0, intY1 - p_intHeight, p_intWidth, p_intHeight);//6
    
    // Jei langas kerta anchorą vertikaliai
    // Laukelio dešinė matosi
    var blnW4OK = g_bln_fFitsInRange(intWindX1, intWindX2, intX2, intX2 + p_intWidth); // Plotis nuo anchoro dešiniojo šono į dešinę
    var blnH3OK = g_bln_fFitsInRange(intWindY1, intWindY2, intY1, intY1 + p_intHeight); // Aukštis nuo anchoro viršaus į apačią
    
    if (blnW4OK && blnH3OK)
        return new clsRegion(intX2, intY1, p_intWidth, p_intHeight);//7
    var blnH4OK = g_bln_fFitsInRange(intWindY1, intWindY2, intY2 - p_intHeight, intY2); // Aukštis nuo viršaus iki anchoro apačios
    
    if (blnW4OK && blnH4OK)
        return new clsRegion(intX2, intY2 - p_intHeight, p_intWidth, p_intHeight);//8
    
    var blnH6OK = g_bln_fFitsInRange(intWindY1, intWindY2, intWindY1, intWindY1 + p_intHeight); // Aukštis nuo lango viršaus į apačią
    var blnH7OK = g_bln_fFitsInRange(intWindY1, intWindY2, intWindY2 - p_intHeight, intWindY2); // Aukštis nuo lango apačios į viršų
    blnH5OK = blnH7OK && g_bln_fFitsInRange(intWindY2 - p_intHeight, intWindY2, intY1, intY2); // Jis turi pilnai liesti anchoro kairę arba dešinę
    if (blnW4OK && blnH5OK)
        return new clsRegion(intX2, intWindY2 - p_intHeight, p_intWidth, p_intHeight);//9
    // Laukelio kairė matosi    
    var blnW5OK = g_bln_fFitsInRange(intWindX1, intWindX2, intX1 - p_intWidth, intX1); // Plotis nuo anchoro kairės į kairę  
    if (blnW5OK && blnH3OK)
        return new clsRegion(intX1 - p_intWidth, intY1, p_intWidth, p_intHeight);//10
    if (blnW5OK && blnH4OK)
        return new clsRegion(intX1 - p_intWidth, intY2 - p_intHeight, p_intWidth, p_intHeight);//11    
    if (blnW5OK && blnH5OK)
        return new clsRegion(intX1 - p_intWidth, intWindY1, p_intWidth, p_intHeight);//12
    
    blnW6OK = blnW6OK && g_bln_fFitsInRange(intX1, intX2, intWindX1, intWindX1); //Dar patikrinam, kad tas taškas, kuris turėtų būti prie meniu yra meniu vietoje    
    if (blnW6OK && blnH1OK)
        return new clsRegion(intWindX1, intY2, p_intWidth, p_intHeight);//13
    blnH6OK = blnH6OK && g_bln_fFitsInRange(intY1, intY2, intWindY1, intWindY1); // Dar patikrinam, kad tas taškas, kuris turėtų būti prie meniu yra meniu vietoje    
    if (blnW4OK && blnH6OK)
        return new clsRegion(intX2, intWindY1, p_intWidth, p_intHeight);//14
    var blnW7OK = g_bln_fFitsInRange(intWindX1, intWindX2, intWindX2 - p_intWidth, intWindX2); // Plotis nuo lango dešiniojo šono į kairę
    blnW7OK = blnW7OK && g_bln_fFitsInRange(intX1, intX2, intWindX2, intWindX2); //Dar patikrinam, kad tas taškas, kuris turėtų būti prie meniu yra meniu vietoje    
    if (blnW7OK && blnH1OK)
        return new clsRegion(intWindX2 - p_intWidth, intY2, p_intWidth, p_intHeight);//15
    if (blnW5OK && blnH6OK)
        return new clsRegion(intX1 - p_intWidth, intWindY1, p_intWidth, p_intHeight);//16
    
    if (blnW6OK && blnH2OK)
        return new clsRegion(intWindX1, intY1 - p_intHeight, p_intWidth, p_intHeight);//17
    blnH7OK = blnH7OK && g_bln_fFitsInRange(intY1, intY2, intWindY2, intWindY2); // Dar patikrinam, kad tas taškas, kuris turėtų būti prie meniu yra meniu vietoje    
    if (blnW4OK && blnH7OK)
        return new clsRegion(intX2, intWindY2 - p_intHeight, p_intWidth, p_intHeight);//18    
    if (blnW7OK && blnH2OK)
        return new clsRegion(intWindX2 - p_intWidth, intY1 - p_intHeight, p_intWidth, p_intHeight);//19
    if (blnW5OK && blnH7OK)
        return new clsRegion(intX1 - p_intWidth, intWindY2 - p_intHeight, p_intWidth, p_intHeight);//20
    
    // Kai jau nebėra vilties ką nors rasti
    return new clsRegion(0, 0, p_intWidth, p_intHeight);//21     
}    

/**
    Nustato ar vidinis itervalas telpa į išorinį intervalą.
    @param p_intOuterR1 Išorinio intervalo mažesnysis rėžis
    @param p_intOuterR2 Išorinio intervalo didesnysis rėžis
    @param p_intInnerR1 Vidinio intervalo mažesnysis rėžis
    @param p_intInnerR2 Vidinio intervalo didesnysis rėžis
*/
function g_bln_fFitsInRange(p_intOuterR1, p_intOuterR2, p_intInnerR1, p_intInnerR2)
{
    return p_intOuterR1 <= p_intInnerR1 && p_intInnerR2 <= p_intOuterR2;
}   

/**
    Metodas globalias koordinates verčia į lokalias atitinkamas platformos atžvilgiu.
    Koordinatės skaičiuojamos nuo dokumento arba nuo pirmo absoliutinio/reliatyvaus tėvo, taip pat:
    IE - absoliutinis tėvas gali būti ir overflow turintis divas.
    FF - reikalinga koordinačių korekcija įskaičiuojant visus scrollTop/scrollLeft objektų 
    esančių iki pirmo absoliutinio/reliatyvaus tėvo.
    @param p_strPlatformId - platformos id arba objektas, kurios atžvilgiu bus skaičiuojamos koordinatės.
    @param p_intGlobalX globali X koordinate.
    @param p_intGlobalY globali Y koordinate.
    @param p_intStartX nurodoma pradine X koordinate(nebutina) (default - 0)                        
    @param p_intStartY nurodoma pradine Y koordinate(nebutina) (default - 0)
    @param p_strItemId elementas kuriam šias koordinates priskirti ( nebūtinas ).
    @returns Gražina koordinačių masyvą [x, y]
    @type int[]
*/
function g_arr_int_fGetCoords(p_strPlatformId, p_intGlobalX, p_intGlobalY, p_intStartX, p_intStartY, p_strItemId)
{
    return (g_arr_int_fGetCoords2(p_strPlatformId, p_intGlobalX, p_intGlobalY, p_intStartX, p_intStartY, p_strItemId));
    var intLocalX = 0;
    var intLocalY = 0;
    if( typeof(p_strPlatformId) != 'object')
        var objPlatform = document.getElementById(p_strPlatformId);
    else
        var objPlatform = p_strPlatformId;
    var objParent = null;
    var blnOverflow = false;
    var objTempPlatform = objPlatform;
    while(objTempPlatform != null && objTempPlatform != document)
    {
        var blnDivOverflow = (objTempPlatform.tagName == 'DIV' && objTempPlatform.style.overflow != '' && objTempPlatform.style.overflow != 'none' || ( cFF && (objTempPlatform.scrollTop != 0 || objTempPlatform.scrollLeft != 0) ) );
        if(objTempPlatform.style.position == 'absolute' ||  objTempPlatform.style.position == 'relative' || blnDivOverflow)
        {
            blnOverflow = blnDivOverflow;
            objParent = objTempPlatform;
            break;
        }
        objTempPlatform = objTempPlatform.parentNode;
        if(objTempPlatform == document)
        {
            objParent = null;
            break;
        }
    }
    if(objParent != null)
    {
        var arr_intGlobalPos = objPosition(objParent);
        if(objParent.style.position == 'absolute' || objParent.style.position == 'relative' || (cIE && blnOverflow)) 
        {
            intLocalX = p_intGlobalX - arr_intGlobalPos[2];
            intLocalY = p_intGlobalY - arr_intGlobalPos[3];
        }   
        else if(cFF && blnOverflow)
        {
            var objTempPlatform = objPlatform;
            var intCorrectionY = 0;
            var intCorrectionX = 0;
            while(objTempPlatform != null && objTempPlatform != document)
            {
                if(objTempPlatform.scrollTop)
                    intCorrectionY += objTempPlatform.scrollTop;
                if(objTempPlatform.scrollLeft)
                    intCorrectionX += objTempPlatform.scrollLeft;
                if(objTempPlatform.style.position == 'absolute' ||  objTempPlatform.style.position == 'relative')
                {
                    objParent = objTempPlatform;
                    break;
                }
                objTempPlatform = objTempPlatform.parentNode;
            }
            var arr_intGlobalPos = objPosition(objParent);
            if(objParent.style.position == 'absolute' || objParent.style.position == 'relative') 
            {
                intLocalX = p_intGlobalX - arr_intGlobalPos[2] - intCorrectionX;
                intLocalY = p_intGlobalY - arr_intGlobalPos[3] - intCorrectionY;
            }
            else
            {
                intLocalX = p_intGlobalX - intCorrectionX;
                intLocalY = p_intGlobalY - intCorrectionY;
            }
        }
        else
        {
            intLocalX = p_intGlobalX;
            intLocalY = p_intGlobalY;
        }
    }
    else
    {
        intLocalX = p_intGlobalX;
        intLocalY = p_intGlobalY;
    }
    
    if(p_strItemId != null)
    {
        var objItem = document.getElementById(p_strItemId);
        objItem.style.left = intLocalX;
        objItem.style.top = intLocalY;
    }
    return( [intLocalX, intLocalY] );
}
//---------------------------------------------------------------
    function g_arr_int_fGetCoords2(p_strPlatformId, p_intGlobalX, p_intGlobalY, p_intStartX, p_intStartY, p_strItemId)
    {
        var intLocalX = 0;
        var intLocalY = 0;
        if( typeof(p_strPlatformId) != 'object')
            var objPlatform = document.getElementById(p_strPlatformId);
        else
            var objPlatform = p_strPlatformId;
        var objParent = null;
        var blnOverflow = false;
        var objTempPlatform = objPlatform;
        while(objTempPlatform != null && objTempPlatform != document)
        {
            var blnDivOverflow = (objTempPlatform.tagName == 'DIV' && objTempPlatform.style.overflow != '' && objTempPlatform.style.overflow != 'none' || ( cFF && (objTempPlatform.scrollTop != 0 || objTempPlatform.scrollLeft != 0) ) );
            if(objTempPlatform.style.position == 'absolute' ||  objTempPlatform.style.position == 'relative' || blnDivOverflow)
            {
                blnOverflow = blnDivOverflow;
                objParent = objTempPlatform;
                break;
            }
            objTempPlatform = objTempPlatform.parentNode;
            if(objTempPlatform == document)
            {
                objParent = null;
                break;
            }
        }
        if (objParent != null)
        {
                        
            var arr_intGlobalPos = g_arr_int_fPosition(objParent);
//2007.08.07 KMarc
//            if(objParent.style.position == 'absolute' || objParent.style.position == 'relative') 
//            {
                intLocalX = p_intGlobalX - arr_intGlobalPos[0];
                intLocalY = p_intGlobalY - arr_intGlobalPos[1];
//            }
//            else
//            {
//                intLocalX = p_intGlobalX;
//                intLocalY = p_intGlobalY;
//            }
        }
        else
        {
            intLocalX = p_intGlobalX;
            intLocalY = p_intGlobalY;
        }
        
        if(p_strItemId != null)
        {
            var objItem = document.getElementById(p_strItemId);
            objItem.style.left = intLocalX;
            objItem.style.top = intLocalY;
        }
        return( [intLocalX, intLocalY] );
    }
    
//////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////      Pozicionavimo funkcijos        //////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
/**
	             - - -   - - - - - - 				
		        |	1  |    2 |    3 |
		        |      |      |      |   
 given point  =====>>> . - - - 	- - - 	
		        |	 4 |    5 |    6 |
		        |      |      |      |
		         - - -   - - -  - - - 
		        |    7 |    8 |    9 | 
		        |      |      |      |
		         - - -   - - -  - - - 
  5 - parent
     metodas tikrina kuri pozicija aplink teviny elementa tinka
     @param p_intX tasko x koordinate
     @param p_intY tasko y koordinate
     @param p_intParentWidth  tevinio lemento plotis
     @param p_intParentHeight tevinio lemento aukstis
     @param p_intWidth issokancio staciakampio plotis
     @param p_intHeight issokancio staciakampio aukstis
     @param p_arrPosition pozicija apie teviny elementa(1,2,3,4,5,6,7,8,88..)
     @param p_strBoundaryObjId ribojancio HTML elemento id (vietoj window)
  
  function finds a suitable position for the popup window 
    				 
*/
function g_hsh_int_fGetCoordsByPosition(p_intX , p_intY, p_intParentWidth, p_intParentHeight, p_intWidth, p_intHeight, p_arrPosition,p_strBoundaryObjId)
{
    var hshArg = new Object();
        hshArg['fits'] = false;
    var intLeft = null;
    var intTop = null;
    
    var intCurrPos = null;
    var blnFoundPosition = false;
    for(var i = 0; i < p_arrPosition.length; i++)
    {
        intCurrPos = p_arrPosition[i];
        var hshATemp = g_hsh_fCheckPosition(p_intX , p_intY, p_intParentWidth, p_intParentHeight, p_intWidth, p_intHeight,intCurrPos,p_strBoundaryObjId);
        if(hshATemp['fits'] == true)
        {
           hshArg['fits'] = true;
           hshArg['intX'] = hshATemp['x'] ;
           hshArg['intY'] = hshATemp['y'] ;
           blnFoundPosition = true;
           break;
        }
    }
    
    if(blnFoundPosition == false)
    {
        switch(p_arrPosition[0]) 
        {
            case 1: 
                hshArg['intX'] = p_intX - p_intWidth;
                hshArg['intY'] = p_intY - p_intHeight;
                break;
            case 2: 
                hshArg['intX'] = p_intX;
                hshArg['intY'] = p_intY - p_intHeight;
                break;
            case 22: 
                hshArg['intX'] = p_intX + p_intParentWidth - p_intWidth;
                hshArg['intY'] = p_intY - p_intHeight;
                break;    
            case 3: 
                hshArg['intX'] = p_intX + p_intParentWidth;
                hshArg['intY'] = p_intY - p_intHeight;
                break;
            case 4: 
                hshArg['intX'] = p_intX - p_intWidth;
                hshArg['intY'] = p_intY;
                break;
             case 44: 
                hshArg['intX'] = p_intX - p_intWidth;
                hshArg['intY'] = p_intY + p_intParentHeight - p_intHeight;
                break;    
            case 5: 
                hshArg['intX'] = p_intX;
                hshArg['intY'] = p_intY;
                break;
            case 6: 
                hshArg['intX'] = p_intX + p_intParentWidth;
                hshArg['intY'] = p_intY;
                break;
            case 66: 
                hshArg['intX'] = p_intX + p_intParentWidth;
                hshArg['intY'] = p_intY + p_intParentHeight - p_intHeight;
                break;    
            case 7: 
                hshArg['intX'] = p_intX - p_intWidth;
                hshArg['intY'] = p_intY + p_intParentHeight;
                break;
            case 8: 
                hshArg['intX'] = p_intX;
                hshArg['intY'] = p_intY + p_intParentHeight;
                break;
            case 88: 
                hshArg['intX'] = p_intX + p_intParentWidth - p_intWidth;
                hshArg['intY'] = p_intY + p_intParentHeight;
                break;    
            case 9: 
                hshArg['intX'] = p_intX + p_intParentWidth;
                hshArg['intY'] = p_intY + p_intParentHeight;
                break;    
            default:
                break;                                
        }
    }
    return hshArg;
}
//-------------------------------------------------------------------------------------------------------------
/**
     metodas tikrina viena pozicija aplink teviny elementa
     @param p_intX tasko x koordinate
     @param p_intY tasko y koordinate
     @param p_intParentWidth  tevinio lemento plotis
     @param p_intParentHeight tevinio lemento aukstis
     @param p_intWidth issokancio staciakampio plotis
     @param p_intHeight issokancio staciakampio aukstis
     @param p_intPosition pozicija apie teviny elementa(1,2,3,4,5,6,7,8,88..)
     @param p_strBoundaryObjId ribojancio HTML elemento id (vietoj window)
*/ 
function g_hsh_fCheckPosition(p_intX , p_intY, p_intParentWidth, p_intParentHeight, p_intWidth, p_intHeight,p_intPosition,p_strBoundaryObjId) 
{
    var hsh_intFitToScreen = null;
    switch(p_intPosition) 
    {
        case 1: 
            hsh_intFitToScreen = g_hsh_int_fFitToScreen(p_intX,p_intY,p_intWidth,p_intHeight,1,p_strBoundaryObjId); 
            break;
        case 2: 
            hsh_intFitToScreen = g_hsh_int_fFitToScreen(p_intX,p_intY,p_intWidth,p_intHeight,4,p_strBoundaryObjId); 
            break;    
        case 22: 
            hsh_intFitToScreen = g_hsh_int_fFitToScreen(p_intX + p_intParentWidth - p_intWidth,p_intY,p_intWidth,p_intHeight,4,p_strBoundaryObjId); 
            break;       
        case 3: 
            hsh_intFitToScreen = g_hsh_int_fFitToScreen(p_intX+p_intParentWidth,p_intY,p_intWidth,p_intHeight,4,p_strBoundaryObjId); 
            break;
        case 4: 
            hsh_intFitToScreen = g_hsh_int_fFitToScreen(p_intX,p_intY,p_intWidth,p_intHeight,2,p_strBoundaryObjId); 
            break; 
        case 44: 
            hsh_intFitToScreen = g_hsh_int_fFitToScreen(p_intX,p_intY+p_intParentHeight-p_intHeight,p_intWidth,p_intHeight,2,p_strBoundaryObjId); 
            break;     
        case 5: 
            hsh_intFitToScreen = g_hsh_int_fFitToScreen(p_intX,p_intY,p_intWidth,p_intHeight,3,p_strBoundaryObjId); 
            break;
        case 6: 
            hsh_intFitToScreen = g_hsh_int_fFitToScreen(p_intX+p_intParentWidth,p_intY,p_intWidth,p_intHeight,3,p_strBoundaryObjId); 
            break; 
        case 66: 
            hsh_intFitToScreen = g_hsh_int_fFitToScreen(p_intX+p_intParentWidth,p_intY+p_intParentHeight-p_intHeight,p_intWidth,p_intHeight,3,p_strBoundaryObjId); 
            break;     
        case 7: 
            hsh_intFitToScreen = g_hsh_int_fFitToScreen(p_intX,p_intY+p_intParentHeight,p_intWidth,p_intHeight,2,p_strBoundaryObjId); 
            break; 
        case 8: 
            hsh_intFitToScreen = g_hsh_int_fFitToScreen(p_intX,p_intY+p_intParentHeight,p_intWidth,p_intHeight,3,p_strBoundaryObjId); 
            break;           
        case 88: 
            hsh_intFitToScreen = g_hsh_int_fFitToScreen(p_intX + p_intParentWidth - p_intWidth,p_intY+p_intParentHeight,p_intWidth,p_intHeight,3,p_strBoundaryObjId); 
            break;                     
        case 9:
            hsh_intFitToScreen = g_hsh_int_fFitToScreen(p_intX+p_intParentWidth,p_intY+p_intParentHeight,p_intWidth,p_intHeight,3,p_strBoundaryObjId); 
            break;    
        default:
            consoleA('no such position');
            break;    
    }
    return hsh_intFitToScreen;    
}
//--------------------------------------------------------------------------------------------------------
/**
    metodas tikrina ar duotas staciakampis duotame taske, duotoje pozicijoje telpa y window, arba y objekta jei nurodytas 'p_strBoundaryObjId'
    metodas naudoja pagrindini metoda 'g_bln_fIsOnScreen' kuris nustato ar duotas taskas yra ekrane.
    norint nustatyti ar staciakampis duotoje pozicijoje telpa ekrane, reikia tikrinti ar jo kampai yra ekrane arba ribojanciame elemente (p_strBoundaryObjId);
    
    @param p_intLeft tasko x koordinate
    @param p_intTop tasko y koordinate
    @param p_intWidth staciakampio plotis
    @param p_intHeight staciakampio aukstis
    @param p_intWantedPos norima pozicija (1,2,3,4)
    @param p_strBoundaryObjId ribojancio HTML elemento id (vietoj window)
    
*/ 
function g_hsh_int_fFitToScreen(p_intLeft,p_intTop,p_intWidth,p_intHeight,p_intWantedPos, p_strBoundaryObjId) 
{
    /*	1	 _ _ _	4				 1  |  4  
		    |	  |                 - - . - -                              
		    |_ _ _|			         2  |  3
	    2			3		
	        points                  positions
    */
    var hsh_int1Fited = new Object();
    hsh_int1Fited['x'] = null; 
    hsh_int1Fited['y'] = null;
    hsh_int1Fited['fits'] = false;
    var hsh_int1 = new Object();
    var hsh_int2 = new Object();
    var hsh_int3 = new Object();
    var hsh_int4 = new Object();
    hsh_int1['x'] = p_intLeft;
    hsh_int1['y'] = p_intTop;
    hsh_int2['x'] = p_intLeft;
    hsh_int2['y'] = p_intTop + p_intHeight;
	
    hsh_int4['x'] = p_intLeft + p_intWidth;
    hsh_int4['y'] = p_intTop;
    hsh_int3['x'] = hsh_int4['x'];
    hsh_int3['y'] = hsh_int2['y'];
    switch(p_intWantedPos) 
    {
	    case 1:
	    // revrersing 43
		    hsh_int4['x'] = hsh_int4['x'] - 2 * p_intWidth;
		    hsh_int3['x'] =  hsh_int4['x'];
	    //	checking 41 reversed
		    var bln41ReversedFits = true;
		    if(g_bln_fIsOnScreen(hsh_int4['x'],hsh_int4['y'],p_strBoundaryObjId)== false) bln41ReversedFits = false;
		    if(g_bln_fIsOnScreen(hsh_int1['x'],hsh_int1['y'],p_strBoundaryObjId)== false) bln41ReversedFits = false;	
		    if(bln41ReversedFits == true)
		    {
		    // reversing 32
			    hsh_int3['y'] = hsh_int3['y'] - 2*p_intHeight;
			    hsh_int2['y'] =  hsh_int3['y'];
		    //checking reversed 32
			    var bln32ReversedFits = true;
			    if(g_bln_fIsOnScreen(hsh_int3['x'],hsh_int3['y'],p_strBoundaryObjId)== false) bln32ReversedFits = false;
			    if(g_bln_fIsOnScreen(hsh_int2['x'],hsh_int2['y'],p_strBoundaryObjId)== false) bln32ReversedFits = false;	
			    if(bln32ReversedFits == true)
			    {
				    hsh_int1Fited['x'] = hsh_int3['x']; 
				    hsh_int1Fited['y'] = hsh_int3['y'];
				    hsh_int1Fited['fits'] = true;
			    }
		    }	
		    break;
	    case 2:
		    var bln12Fits = true;
	    // checking 12
		    if(g_bln_fIsOnScreen(hsh_int1['x'],hsh_int1['y'],p_strBoundaryObjId)== false) bln12Fits = false;
		    if(g_bln_fIsOnScreen(hsh_int2['x'],hsh_int2['y'],p_strBoundaryObjId)== false) bln12Fits = false;
		    if(bln12Fits == true)
		    {
		    // revrersing 43
			    hsh_int4['x'] = hsh_int4['x'] - 2*p_intWidth;
			    hsh_int3['x'] =  hsh_int4['x'];
		    //	checking 43 reversed
			    var bln43ReversedFits = true;
			    if(g_bln_fIsOnScreen(hsh_int4['x'],hsh_int4['y'],p_strBoundaryObjId)== false) bln43ReversedFits = false;
			    if(g_bln_fIsOnScreen(hsh_int3['x'],hsh_int3['y'],p_strBoundaryObjId)== false) bln43ReversedFits = false;	
			    if(bln43ReversedFits == true)
			    {
				    hsh_int1Fited['x'] = hsh_int4['x']; 
				    hsh_int1Fited['y'] = hsh_int4['y'];
				    hsh_int1Fited['fits'] = true;
			    }
		    }
		    break;
	    case 3:
		    var bln14Fits = true;
		    // start checking 14
		    if(g_bln_fIsOnScreen(hsh_int1['x'],hsh_int1['y'],p_strBoundaryObjId)== false) bln14Fits = false;
		    if(g_bln_fIsOnScreen(hsh_int4['x'],hsh_int4['y'],p_strBoundaryObjId)== false) bln14Fits = false;
		    if(bln14Fits == true)
		    {
		    // checking 23
			    var bln23Fits = true;
			    if(g_bln_fIsOnScreen(hsh_int2['x'],hsh_int2['y'],p_strBoundaryObjId)== false) bln23Fits = false;
			    if(g_bln_fIsOnScreen(hsh_int3['x'],hsh_int3['y'],p_strBoundaryObjId)== false) bln23Fits = false;
			    if(bln23Fits == true)
			    {
				    hsh_int1Fited['x'] = hsh_int1['x']; 
				    hsh_int1Fited['y'] = hsh_int1['y'];
				    hsh_int1Fited['fits'] = true;
			    }
		    }
		    break;
	    case 4:
		    var bln14Fits = true;
		    // checking 14
		    if(g_bln_fIsOnScreen(hsh_int1['x'],hsh_int1['y'],p_strBoundaryObjId)== false) bln14Fits = false;
		    if(g_bln_fIsOnScreen(hsh_int4['x'],hsh_int4['y'],p_strBoundaryObjId)== false) bln14Fits = false;
		    if(bln14Fits == true)
		    {
			    // reversing 23 
			    hsh_int2['y'] = hsh_int2['y'] - 2*p_intHeight;
			    hsh_int3['y'] = hsh_int2['y'] ;
			    // checking reversed 23
			    var bln23ReversedFits = true;
			    if(g_bln_fIsOnScreen(hsh_int2['x'],hsh_int2['y'],p_strBoundaryObjId)== false) bln23ReversedFits = false;
			    if(g_bln_fIsOnScreen(hsh_int3['x'],hsh_int3['y'],p_strBoundaryObjId)== false) bln23ReversedFits = false;
			    if(bln23ReversedFits == true)	
			    {
				    hsh_int1Fited['x'] = hsh_int2['x']; 
				    hsh_int1Fited['y'] = hsh_int2['y'];
				    hsh_int1Fited['fits'] = true;
			    }
		    }
    }
    return hsh_int1Fited;
}

/**
    Nustato elemento poziciją
*/
function g_arr_int_fPosition(p_objElement)
{
	var objElement = p_objElement;
	if (!objElement)
	    objElement = document.body;    
	if (typeof(objElement) == 'string')
	{
	    objElement = document.getElementById(objElement);   
	}
	if (objElement == null)
	    objElement = document.body;
	var l=0; var t=0; var w=0; var h=0;
	w = objElement.offsetWidth;
    h = objElement.offsetHeight;
    //l += objElement.scrollLeft;
    //t += objElement.scrollTop;
	if (objElement.offsetParent)
	{
		for (posX = 0, posY = 0; objElement.offsetParent; objElement = objElement.offsetParent)
		{
			if (objElement.id == 'minwidthcont' || objElement.className == 'minwidthcont') // Padaryta tam, kad ant IE panaudotas minWidth mechanizmas neišdarkytų pozicijos. Objektas, kurio klasė yra minwidthcont turi offsetLeft lygų -[min_width] (pvz.: -800), taigi į jį reikia neatsižvelgti.
			    continue;
			l += objElement.offsetLeft - objElement.scrollLeft;
			t += objElement.offsetTop - objElement.scrollTop;
		}
	}
	return([l, t, w, h]);
}

function g_obj_fGetRegion(p_objElement)
{
    return new clsRegion(g_arr_int_fPosition(p_objElement));
}

function g_arr_int_fMakeRelative(p_arr_intGlobalCoords, p_strPlatformId)
{
    var arr_intPosition = g_arr_int_fPosition(p_strPlatformId);
    return [p_arr_intGlobalCoords[0] - arr_intPosition[0], p_arr_intGlobalCoords[1] - arr_intPosition[1]];
}

function g_obj_fMakeRelative(p_objGlobalCoords, p_strPlatformId)
{
    var objRegion = g_obj_fGetRegion(p_strPlatformId);
    return new clsPoint(p_objGlobalCoords.X - objRegion.X, p_objGlobalCoords.Y - objRegion.Y);
}


/**
    Nustato ar pelė yra viduje tam nurodyto elemento.
    @param p_objEvent vykstantis įvykis;
    @param p_objDOMObject DOM elementas, kuriam atliekamas testas;
*/
function g_bln_fIsInside(p_objEvent, p_objDOMObject)
{
    var arr_intMouseCoords = getMouse(p_objEvent);
    var arr_intRectCoords = g_arr_int_fPosition(p_objDOMObject);
    return (arr_intMouseCoords[0] >= arr_intRectCoords[0] && arr_intMouseCoords[0] <= arr_intRectCoords[0] + arr_intRectCoords[2] &&
        arr_intMouseCoords[1] >= arr_intRectCoords[1] && arr_intMouseCoords[1] <= arr_intRectCoords[1] + arr_intRectCoords[3]);
}

/**
    Nustato ar pelė yra viduje tam nurodyto elemento, tikrina griežtai, t.y. pelė turi būti griežtai viduje.
    @param p_objEvent vykstantis įvykis;
    @param p_objDOMObject DOM elementas, kuriam atliekamas testas;
*/
function g_bln_fIsInsideStrict(p_objEvent, p_objDOMObject)
{
    var arr_intMouseCoords = getMouse(p_objEvent);
    var arr_intRectCoords = g_arr_int_fPosition(p_objDOMObject);
    return (arr_intMouseCoords[0] > arr_intRectCoords[0] && arr_intMouseCoords[0] < arr_intRectCoords[0] + arr_intRectCoords[2] &&
        arr_intMouseCoords[1] > arr_intRectCoords[1] && arr_intMouseCoords[1] < arr_intRectCoords[1] + arr_intRectCoords[3]);
}

/**
    Taško objektas.
    Turi tokius konstruktorius:
    var objPoint = new clsPoint(); 
    var objPoint = new clsPoint([int, int]);
    var objPoint = new clsPoint({X:int, Y:int});
    var objPoint = new clsPoint(int, int[, ...]);
    
    X koordinatė pasiekima iš nario - X;
    Y koordinatė pasiekima iš nario - Y;
*/
function clsPoint()
{
    if (arguments.length == 0 || arguments[0] == null)
    {
        this.X = 0;
        this.Y = 0;
    }
    else
    if (arguments.length == 1)
    {
        if (g_bln_fIsArray(arguments[0]))
        {
            this.X = arguments[0][0];
            this.Y = arguments[0][1];
        }
        else
        {
            this.X = arguments[0].X;
            this.Y = arguments[0].Y;
        }
    }
    else
    if (arguments.length >= 2)
    {
        this.X = arguments[0];
        this.Y = arguments[1];
    }
}

/**
    Regiono objektas.
    Turi tokius konstruktorius:
        var objRegion = new clsRegion(); 
        var objRegion = new clsRegion([int, int, int, int]);
        var objRegion = new clsRegion({X:int, Y:int, W:int, H:int});
        var objRegion = new clsRegion(int, int, int, int[, ...]);
*/
function clsRegion()
{
    if (arguments.length == 0 || arguments[0] == null)
    {
        this.X = 0;
        this.Y = 0;
        this.W = 0;
        this.H = 0;
    }
    else
    if (arguments.length == 1)
    {
        if (g_bln_fIsArray(arguments[0]))
        {
            this.X = arguments[0][0];
            this.Y = arguments[0][1];
            this.W = arguments[0][2];
            this.H = arguments[0][3];
        }
        else
        {
            this.X = arguments[0].X;
            this.Y = arguments[0].Y;
            this.W = arguments[0].W;
            this.H = arguments[0].H;
        }
    }
    else
    if (arguments.length >= 4)
    {
        this.X = arguments[0];
        this.Y = arguments[1];
        this.W = arguments[2];
        this.H = arguments[3];
    }
}

clsRegion.prototype.g_bln_fContainsX = function(p_objPoint)
{
    return (p_objPoint.X >= this.X && p_objPoint.X <= this.X + this.W);
}

clsRegion.prototype.g_bln_fContainsY = function(p_objPoint)
{
    return (p_objPoint.Y >= this.Y && p_objPoint.Y <= this.Y + this.H);
}

clsRegion.prototype.g_bln_fContains = function(p_objPoint)
{
    return (p_objPoint.X >= this.X && p_objPoint.X <= this.X + this.W 
        && p_objPoint.Y >= this.Y && p_objPoint.Y <= this.Y + this.H);
}

clsRegion.prototype.g_int_fSize = function()
{
    return Math.abs(this.W) * Math.abs(this.H);
}
    

// Pozicijos nustatymo funkcijos \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

//<><><>////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////                                                 ///////////////
////////////////             Matematinės funkcijos               ///////////////
////////////////                                                 ///////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

function g_arr_fFormatSize(p_intValue)
{
    if (p_intValue < 1024)
    {
        return [p_intValue, 'KB'];
    }
    else
    {
        return [g_int_fSizeInSpecUnits(p_intValue, 'MB'), 'MB'];
    }
}
    
function g_int_fSizeInSpecUnits (p_intValue, p_strUnit)
{
    if (p_strUnit.toLowerCase() == 'mb')
    {
        return Math.round(p_intValue / 1024 * 10) / 10;
    }
    else
        return p_intValue;
}

function g_str_fFormatNumber(p_fltValue)
{
    var strValue = '' + p_fltValue;
    var arr_strParts = strValue.split('.');
    arr_strParts = g_arr_str_fFormatFraction(arr_strParts);
    arr_strParts = g_arr_str_fFormatIntegralPart(arr_strParts);
    var strResult = arr_strParts[0];
    if (arr_strParts[1] != '')
        strResult += cDecimalSymbol + arr_strParts[1];
    return strResult;
    
}

function g_flt_fGetRealValue(p_strDisplayValue)
{
    var strDisplay = p_strDisplayValue;
    var objSepReg = new RegExp('[' + cDecimalSymbol + ']', 'g');
    var objGroupReg = new RegExp('[' + cGroupingSymbol + ']', 'g');
    strDisplay = strDisplay.replace(objGroupReg, '');
    strDisplay = strDisplay.replace(objSepReg, '.'); // atverčiam trupmenos skirtuką į tašką
    return parseFloat(strDisplay);
}

/**
    Suformatuoja trukmeninę dalį.
*/
function g_arr_str_fFormatFraction(p_arr_strParts)
{
    var strFraction = p_arr_strParts[1];
    if (strFraction == null)
        strFraction = '';
    var intPrecision = 2
    var blnDisplayTrailingZero = false;
    if (intPrecision > 0)
    {
        if (strFraction.length < intPrecision)
        {
            if (blnDisplayTrailingZero)
            {
                strFraction += g_str_fGetJoinedString('0', intPrecision - strFraction.length);  
            }
        }
        else    // Daugiau arba lygu
        {
            strFraction = strFraction.substr(0, intPrecision);
        }
    }
    else    // gal reiktų kažką daryti, jei intPrecision būtų < 0, bet čia ateičiai
    {
        strFraction = '';        
    }
    return [p_arr_strParts[0], strFraction];
}    

/**
    Suformatuoja sveiką dalį
*/    
function g_arr_str_fFormatIntegralPart(p_arr_strParts)
{
    var strIntegral = p_arr_strParts[0];
    if (!strIntegral)
        strIntegral = '0';
    var blnHasMinus = false;
    if (strIntegral.charAt(0) == '-')
    {
        blnHasMinus = true;
        strIntegral = strIntegral.substr(1); // paimam viską be minuso
    }
    var strFormed = '';
    var intLength = strIntegral.length;
    var intGrouping = 1;
    var strGroupingSymbol = cGroupingSymbol;
    if (intGrouping == 1) // Kas tūkstančius
    {
        var i = intLength % 3;
        strFormed = strIntegral.substr(0, i);
        for (; i < intLength; i += 3)
        {
            if (strFormed != '')
                strFormed += strGroupingSymbol;
            strFormed += strIntegral.substr(i, 3);
        }
        strIntegral = strFormed;
    }
    else if (intGrouping == 2) // Pirmas kas tūkstančius, paskui kas šimtus
    {
        if (intLength <= 3)
        {
            strFormed = strIntegral;
        }
        else
        {
            intLength -= 3;
            var i = intLength % 2;
            strFormed = strIntegral.substr(0, i);
            for (; i < intLength; i += 2)
            {
                if (strFormed != '')
                    strFormed += strGroupingSymbol;
                strFormed += strIntegral.substr(i, 2);
            }   
            if (strFormed != '')
                strFormed += strGroupingSymbol;
            strFormed += strIntegral.substr(i, 3);
        }   
        strIntegral = strFormed; 
    }
    return [strIntegral, p_arr_strParts[1]];
}

/**
    Vercia desimtaini skaiciu i sesioliktaini pvz '246'->'F6',
    galima kad grazintu su atitinkamu priekiu pvz 0x ar belekokiu koki paduosi
    dec - desimtainis skaicius (0-255)
    priekis - prie grazinamo 26-ainio pridedamas priekyje (tiesiog)
*/
function decToHex(dec, priekis)
{
    dec = parseInt(dec, 10);
    if (!isNaN(dec)) 
    {
        hexChars = "0123456789ABCDEF";
        if (dec > 255) 
        {
            return(null);
        }
        var i = dec % 16;
        var j = (dec - i) / 16;
        result = '';
        if(priekis!=null)
        {
			result+=priekis;
        }
        result += hexChars.charAt(j) + hexChars.charAt(i);
        return(result);
    } 
    else 
    {
        return(null);
    }
}


function clsBase64()
{
    var hshSymbols = new Object();
    hshSymbols['A'] = 0;
    hshSymbols['B'] = 1;
    hshSymbols['C'] = 2;
    hshSymbols['D'] = 3;
    hshSymbols['E'] = 4;
    hshSymbols['F'] = 5;
    hshSymbols['G'] = 6;
    hshSymbols['H'] = 7;
    hshSymbols['I'] = 8;
    hshSymbols['J'] = 9;
    hshSymbols['K'] = 10;
    hshSymbols['L'] = 11;
    hshSymbols['M'] = 12;
    hshSymbols['N'] = 13;
    hshSymbols['O'] = 14;
    hshSymbols['P'] = 15;
    hshSymbols['Q'] = 16;

    hshSymbols['R'] = 17;
    hshSymbols['S'] = 18;
    hshSymbols['T'] = 19;
    hshSymbols['U'] = 20;
    hshSymbols['V'] = 21;
    hshSymbols['W'] = 22;
    hshSymbols['X'] = 23;
    hshSymbols['Y'] = 24;
    hshSymbols['Z'] = 25;
    hshSymbols['a'] = 26;
    hshSymbols['b'] = 27;
    hshSymbols['c'] = 28;
    hshSymbols['d'] = 29;
    hshSymbols['e'] = 30;
    hshSymbols['f'] = 31;
    hshSymbols['g'] = 32;
    hshSymbols['h'] = 33;

    hshSymbols['i'] = 34;
    hshSymbols['j'] = 35;
    hshSymbols['k'] = 36;
    hshSymbols['l'] = 37;
    hshSymbols['m'] = 38;
    hshSymbols['n'] = 39;
    hshSymbols['o'] = 40;
    hshSymbols['p'] = 41;
    hshSymbols['q'] = 42;
    hshSymbols['r'] = 43;
    hshSymbols['s'] = 44;
    hshSymbols['t'] = 45;
    hshSymbols['u'] = 46;
    hshSymbols['v'] = 47;
    hshSymbols['w'] = 48;
    hshSymbols['x'] = 49;
    hshSymbols['y'] = 50;

    hshSymbols['z'] = 51;
    hshSymbols['0'] = 52;
    hshSymbols['1'] = 53;
    hshSymbols['2'] = 54;
    hshSymbols['3'] = 55;
    hshSymbols['4'] = 56;
    hshSymbols['5'] = 57;
    hshSymbols['6'] = 58;
    hshSymbols['7'] = 59;
    hshSymbols['8'] = 60;
    hshSymbols['9'] = 61;
    hshSymbols['+'] = 62;
    hshSymbols['/'] = 63;

    //---------------------------------------------------
    this.g_str_fConvertToNormal = function(p_strBase64String)
    {
        var strAts = '';
        for(var i = 0;i < p_strBase64String.length;i++)
        {
            var strChar = p_strBase64String.charAt(i);
            if(strChar != '=')
            {
                var intCode = hshSymbols[strChar];
                strAts += str_fIntegerTo6bit(intCode);
            }
        }
        var arr_intDec = arr_int_fBitsToBytes(strAts);
        for(var i = 0;i < arr_intDec.length;i++)
        {
            arr_intDec[i] = decToHex(arr_intDec[i], '');
        }
        var strAts = '0x';
        for(var i = 0;i < Math.min(8, arr_intDec.length);i++)
        {
            strAts += arr_intDec[i];
        }
        return(strAts);
    }
    //---------------------------------------------------
    function arr_int_fBitsToBytes(p_strBits)
    {
        var arr_intAts = new Array();
        var arr_intSvoriai = new Array(128, 64, 32, 16, 8, 4, 2, 1);
        while(true)
        {
            var strBaitas = p_strBits.slice(0, Math.min(8, p_strBits.length) );
            var intSuma = 0;
            for(var i = 0;i < strBaitas.length;i++)
            {
                var intKiek = parseInt( strBaitas.charAt(i) );
                intSuma += intKiek * arr_intSvoriai[i];
            }
            arr_intAts.push(intSuma);
            if(p_strBits.length > 8)
            {
                p_strBits = p_strBits.substring(8, p_strBits.length);
            }
            else
            {
                break;
            }
        }
        return(arr_intAts);
    }
    //---------------------------------------------------
    function str_fIntegerTo6bit(p_intInteger)
    {
        var strAts = '';
        var arr_intSvoriai = new Array(32, 16, 8, 4, 2, 1);
        for(var i = 0;i < arr_intSvoriai.length; i++)
        {
            if(p_intInteger >= arr_intSvoriai[i])
            {
                strAts += '1';
                p_intInteger -= arr_intSvoriai[i];
            }
            else
            {
                strAts += '0';
            }
        }
        return(strAts);
    }
//---------------------------------------------------
}
     
/**
    Objektų, kurie turi < operatorių palyginimas. Rikiuojant skaičių masyvus reikėtų ją nurodyti 
    sort funkcijos parametre. Jeigu reikia lyginti pagal tam tikrą lauką arba pagal kelis, tai reiktų 
    pasirašyti panašią funkciją.
    @author Kęstutis Malinauskas
    @param p_objA Palyginamas objektas A.
    @param p_objB Palyginamas objektas B.
    @returns Jei A < B, tai gražins neigiamą skaičių(-2), jei A = B - gražins 0, jei A > B - gražins teigiamą skaičių (2)
    @type int
*/
function g_int_fComparator(p_objA, p_objB)
{
    return (p_objB < p_objA) - (p_objA < p_objB);
}

function asciiToUrl(eilute)
{
	if(eilute !=null)
	{
		var ss = /\&\#[0-9]{1,3}\;/g;
		var ra = eilute.match(ss);
		var ats=eilute;
		if(ra!=null)
		{
			for(r=0;r<ra.length;r++)
			{
				ats = ats.replace( ra[r], '%'+decToHex(ra[r].substr(2,ra[r].length-3)) );
			}
		}
		return(ats);
	}
	return(null);
}

/**
    Patikrina ar paduota reikšmė yra integer tipo ar ne.
*/    
function g_bln_fIsInt(p_objValue) 
{
    var intValue = parseInt(p_objValue);
    if (isNaN(intValue)) return false;
    return p_objValue == intValue && p_objValue.toString() == intValue.toString();
}

// Matematinės funkcijos \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

//<><><>////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////                                                 ///////////////
////////////////          Funkcijų iškvietimo tvarkymas          ///////////////
////////////////                                                 ///////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

/**
    Leidžia įvykiui priskirti funkciją, kuri neleakintų
    http://laurens.vd.oever.nl/weblog/items2005/closures/
    @Brought to you by KM
    @Version 1 2006.10.20
*/
Function.prototype.closure = function(obj)
{
  // Init object storage.
  if (!window.__objs)
  {
    window.__objs = [];
    window.__funs = [];
  }

  // For symmetry and clarity.
  var fun = this;

  // Make sure the object has an id and is stored in the object store.
  var objId = obj.__objId;
  if (!objId)
    __objs[objId = obj.__objId = __objs.length] = obj;

  // Make sure the function has an id and is stored in the function store.
  var funId = fun.__funId;
  if (!funId)
    __funs[funId = fun.__funId = __funs.length] = fun;
  
  // Init argument storage.
  if (!obj.__args)
    obj.__args = [];

  // See if we previously created a closure for this object/function pair.
  obj.__args[funId] = [];
  for (var i = 1, intLength = arguments.length; i < intLength; i++)
  {
    obj.__args[funId].push(arguments[i]);    
  }
  // Init closure storage.
  if (!obj.__closures)
    obj.__closures = [];

  // See if we previously created a closure for this object/function pair.
  var closure = obj.__closures[funId];
  if (closure)
    return closure;
  
  // Clear references to keep them out of the closure scope.
  obj = null;
  fun = null;

  // Create the closure, store in cache and return result.
  return __objs[objId].__closures[funId] = function (p_objEvent)
  {
    if (typeof(ftypeof) != 'function')
        return null;   
    if (ftypeof(p_objEvent) == 'event')// instanceof Event)
    {
        var hshArg = {};
        var objElement = getSrcElement(p_objEvent)
        hshArg['event'] = p_objEvent;
        hshArg['object'] = objElement;
        if (__objs[objId])
        {
            hshArg['args'] = __objs[objId].__args[funId];
        }
        return __funs[funId].apply(__objs[objId], [hshArg]);
    }
    // else
    return __funs[funId].apply(__objs[objId], arguments);   
  };
};

/**
    @class
    Sukuria metodo iškvietimo objektą
    @param p_objContext - Objektas, kuriam priklauso kviečiamas metodas. Jei null, tai laikoma, kad tai yra window objektas
    @param p_objFunction - Funkcija, kurią reikia kviesti, tai arba jos pavadinimas, arba funkcijos objektas
    @param p_intDelay - Kiek laukti prieš kviečiant metodą
    @param arguments[3 ...] - Funkcijos argumentai, kurie bus perduoti į funkciją kvietimo metu
    @author KM
    @version 1 2006.10.14
*/
function clsFunctionCaller(p_objFunction, p_objContext, p_intDelay)
{
    var arr_objTempArray = arguments;
    if (arguments.length == 1)  // Jei viskas nurodyta viename masyve
    {
        arr_objTempArray = arguments[0];    
        p_objFunction = arr_objTempArray[0];
        p_intDelay = arr_objTempArray[2];
        p_objContext = arr_objTempArray[1];           
    }
    
    this.g_intId = 'AsyncCaller' + (g_objAsyncCaller.g_intCounter++);
    this.g_intDelay = p_intDelay;
    this.objFunction = p_objFunction;
    this.g_strTimerId = 0;
    this.objContext = p_objContext;
    this.arr_objArguments = [];   
    for (var i = 3; i < arr_objTempArray.length; i++)  // Surenka likusius argumentus
    {
        this.arr_objArguments.push(arr_objTempArray[i]);    
    }
    this.blnHasBeenCalled = false;
    this.fCallBack = null;
    this.g_objReturn = null;
    this.g_fResult = null;
    
    /**
        Iškviečia funkciją sinchroniškai
    */
    this.g_fExecute = function()
    {
        delete g_objAsyncCaller.g_hshPendingCalls[this.g_intId]; 
        if (this.objContext == null)    // Jei funkcijos kontekstas yra null, tai laikoma, kad tai window objektas
            this.objContext = window;
        
        if (typeof(this.objFunction) == 'string') // Jei funkcija pateikta kaip eilutė, tai susirandam tą funkciją
            this.objFunction = this.objContext[this.objFunction];          
        
        if (typeof(this.objFunction) == 'function')     // Jei funkcija rasta, tai ją iškviečiam
            this.g_fResult = this.objFunction.apply(this.objContext, this.arr_objArguments); 
        
        this.blnHasBeenCalled = true;
        Listener.fire(this, 'onEnd', [this.g_fResult]);
    }
    
    /**
        Nurodo funkciją, kuri bus iškviesta po to, kai bus įvykdyta pagrindinė funkcija.
    */
    this.g_fAddExecutionEndListener = function(p_fFunction, p_objContext)
    {
        Listener.add(this, 'onEnd', p_fFunction, p_objContext, false);
    }
    
    /**
        Atšaukia funkcijos vykdymą
    */
    this.g_fCancel = function()
    {
        clearTimeout(this.g_strTimerId);
        g_objAsyncCaller.g_hshPendingCalls[this.g_intId] == null;    
    }    
    
    /**
        Parodo ar funkcija jau buvo kviesta
    */
    this.g_bln_fHasBeenCalled = function()
    {
        return this.blnHasBeenCalled;    
    }
    
    /**
        Paleidžia funkcijos iškvietimo taimerį iš naujo. Jei taimeris jau eina, tai paleidžia iš naujo.
    */
    this.g_fStartCounter = function()
    {
        if (arguments.length > 0)
            this.arr_objArguments = arguments;
        if (!g_objAsyncCaller.g_hshPendingCalls[this.g_intId])
            g_objAsyncCaller.g_hshPendingCalls[this.g_intId] = this;
        else      
        {
            clearTimeout(this.g_strTimerId);
        }    
        g_objAsyncCaller.g_hshPendingCalls[this.g_intId].g_strTimerId = 
            setTimeout('g_objAsyncCaller.g_hshPendingCalls["' + this.g_intId + '"].g_fExecute()', this.g_intDelay); 
    }
     
    g_objAsyncCaller.g_hshPendingCalls[this.g_intId] = this;
}


//----------------------------------------------------------------------------------------------
/**
    Globalus asinchroninio iškvietimo objektas.
    @author KM
    @version 1 2006.10.14
    
    Panaudojimo pavyzdys.
    
    function TestClass(p_intA)
    {
        this.A = p_intA;
        this.Funkcija2 = function(p_arg, arg1)
        {
        }
    }

    function Funkcija1(p_arg)
    {
        console('Paprasta funkcija');
        console('p_arg: ' + p_arg);
    }
    
    function AsyncTest()
    {
        var objCaller = new clsFunctionCaller(Funkcija1, null, 700, 1);
        g_objAsyncCaller.g_fAsyncCall(objCaller);
        
        var objCaller = new clsFunctionCaller('Funkcija1', null, 500, 2);
        g_objAsyncCaller.g_fAsyncCall(objCaller);
        
        var test = new TestClass('pirmas');
        
        var objCaller = new clsFunctionCaller('Funkcija2', test, 1000, 3);
        objCaller.g_fSetCallback(Funkcija1);
        g_objAsyncCaller.g_fAsyncCall(objCaller);
        
        var objCaller = new clsFunctionCaller(test.Funkcija2, test, 200, 4, 6);
        g_fAsyncCall(objCaller);
        objCaller.g_fCancel();
        
        var objCaller = new clsFunctionCaller(test.Funkcija2, test, 200);
        objCaller.g_fStartCounter('arg1', 'arg2', 'arg3');
        
        g_fAsyncCallImediate(test.Funkcija2, null, 0, 5);
        
    }
*/
g_objAsyncCaller = {};
g_objAsyncCaller.g_intCounter = 0;
g_objAsyncCaller.g_hshPendingCalls = {};

/**
    Nustato iškviesti clsFunctionCaller objekto metodą g_fExecute po tam tikro laiko g_intDelay.
    @param p_objFunctionCaller {clsFunctionCaller} Funkcijos iškvietimo objektas.
*/
function g_fAsyncCall(p_objFunctionCaller)
{
    // Jei egzistuoja toks objektas
    if (g_objAsyncCaller.g_hshPendingCalls[p_objFunctionCaller.g_intId])
    {
        if (g_objAsyncCaller.g_hshPendingCalls[p_objFunctionCaller.g_intId].g_strTimerId != 0)
            clearTimeout(this.g_strTimerId);
        g_objAsyncCaller.g_hshPendingCalls[p_objFunctionCaller.g_intId].g_strTimerId = 
            setTimeout('g_objAsyncCaller.g_hshPendingCalls["' + p_objFunctionCaller.g_intId + '"].g_fExecute()',
                p_objFunctionCaller.g_intDelay);    
    }
}
g_objAsyncCaller.g_fAsyncCall = g_fAsyncCall;

/**
    Sukuria ir iš karto iškviečia funkciją asinchroniškai. 
    Argumentai tokie patys, kaip clsFunctionCaller konstruktoriaus.
    @returns Sukurtąjį funkcijos kvietimo objektą.
    @type clsFunctionCaller objektas
*/
function g_obj_fAsyncCallImediate()
{
    var arr_objArguments = [];
    for (var i = 0, intLength = arguments.length; i < intLength; i++)  // Surenka argumentus
    {
        arr_objArguments.push(arguments[i]);    
    }
    var objCaller = new clsFunctionCaller(arr_objArguments);//new clsFunctionCaller(arr_objArguments);//new clsFunctionCaller.apply(window, arguments);
    g_objAsyncCaller.g_fAsyncCall(objCaller); 
    return objCaller;       
}
g_objAsyncCaller.g_fAsyncCallImediate = g_obj_fAsyncCallImediate;

///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////           Periodinio funkcijų kvietimo objektas       /////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////

/**
    @class
    Sukuria metodo iškvietimo objektą
    @param p_objContext - Objektas, kuriam priklauso kviečiamas metodas. Jei null, tai laikoma, kad tai yra window objektas
    @param p_objFunction - Funkcija, kurią reikia kviesti, tai arba jos pavadinimas, arba funkcijos objektas
    @param p_intPeriod - Koks yra iškvietimo periodas
    @param arguments[3 ...] - Funkcijos argumentai, kurie bus perduoti į funkciją kvietimo metu
    
    Panaudojimo pavyzdys:
        Paleidimas:
        if (objIntervalCaller == null)
        {
            var objTemp = new clsTempClass();
            objIntervalCaller = new clsIntervalCaller(objTemp.g_fFunction, objTemp, 1000);
        }
        objIntervalCaller.g_fStartInterval();
        
        Sustabdymas:
        if (objIntervalCaller)
        {
            objIntervalCaller.g_fCancel();
        }
    Paleisti ir sustabdyti galima n kartų.
    @author KM
    @version 1 2006.10.14
*/
function clsIntervalCaller(p_objFunction, p_objContext, p_intPeriod)
{
    var arr_objTempArray = arguments;
    if (arguments.length == 1)  // Jei viskas nurodyta viename masyve
    {
        arr_objTempArray = arguments[0];    
        p_objFunction = arr_objTempArray[0];
        p_intPeriod = arr_objTempArray[2];
        p_objContext = arr_objTempArray[1];           
    }
    
    this.g_intId = 'IntervalCaller' + (g_objIntervalCaller.g_intCounter++);
    this.g_intPeriod = p_intPeriod;
    this.objFunction = p_objFunction;
    this.g_strIntervalId = 0;
    this.objContext = p_objContext;
    this.arr_objArguments = [];   
    for (var i = 3; i < arr_objTempArray.length; i++)  // Surenka likusius argumentus
    {
        this.arr_objArguments.push(arr_objTempArray[i]);    
    }
    this.blnHasBeenCalled = false;
    this.intCallCount = 0;
    this.fCallBack = null;
    this.g_objReturn = null;
    this.g_fResult = null;
    
    /**
        Iškviečia funkciją sinchroniškai
    */
    this.g_fExecute = function()
    {
        if (this.objContext == null)    // Jei funkcijos kontekstas yra null, tai laikoma, kad tai window objektas
            this.objContext = window;
        
        if (typeof(this.objFunction) == 'string') // Jei funkcija pateikta kaip eilutė, tai susirandam tą funkciją
            this.objFunction = this.objContext[this.objFunction];          
        
        if (typeof(this.objFunction) == 'function')     // Jei funkcija rasta, tai ją iškviečiam
            this.g_fResult = this.objFunction.apply(this.objContext, this.arr_objArguments); 
        
        this.blnHasBeenCalled = true;
        this.intCallCount++;
        Listener.fire(this, 'onEnd', [this.g_fResult]);
    }
    
    /**
        Nurodo funkciją, kuri bus iškviesta po to, kai bus įvykdyta pagrindinė funkcija.
    */
    this.g_fAddExecutionEndListener = function(p_fFunction, p_objContext)
    {
        Listener.add(this, 'onEnd', p_fFunction, p_objContext, false);
    }
    
    /**
        Atšaukia funkcijos vykdymą
    */
    this.g_fCancel = function()
    {
        clearInterval(this.g_strIntervalId);
        g_objIntervalCaller.g_hshIntervals[this.g_intId] == null;    
    }    
    
    /**
        Parodo ar funkcija jau buvo kviesta
    */
    this.g_bln_fHasBeenCalled = function()
    {
        return this.blnHasBeenCalled;    
    }
    
    /**
        Paleidžia funkcijos iškvietimo taimerį iš naujo. Jei taimeris jau eina, tai paleidžia iš naujo.
    */
    this.g_fStartInterval = function()
    {
        if (arguments.length > 0)
            this.arr_objArguments = arguments;
        if (!g_objIntervalCaller.g_hshIntervals[this.g_intId])
            g_objIntervalCaller.g_hshIntervals[this.g_intId] = this;
        else      
        {
            clearInterval(this.g_strIntervalId);
        }    
        g_objIntervalCaller.g_hshIntervals[this.g_intId].g_strIntervalId = 
            setInterval('g_objIntervalCaller.g_hshIntervals["' + this.g_intId + '"].g_fExecute()', this.g_intPeriod); 
    }
     
    g_objIntervalCaller.g_hshIntervals[this.g_intId] = this;
}


//----------------------------------------------------------------------------------------------
/**
    Globalus intervalinio iškvietimo objektas.
    @author KM
    @version 1 2007.08.14
*/
g_objIntervalCaller = {};
g_objIntervalCaller.g_intCounter = 0;
g_objIntervalCaller.g_hshIntervals = {};


// Funkcijų iškvietimo tvarkymas \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

//<><><>////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////                                                 ///////////////
////////////////           Langų kvietimo funkcijos, ir          ///////////////
////////////////     funkcijos, reikalingos langų hierarchijai   ///////////////
////////////////                                                 ///////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

/** Reikšmė kurią grąžinam į seną langą*/
var _ret = null;
/** Reikšmė kurią perduodam į naują langą*/
var _val = null;
/** Funkcija kurią kviesim senajame lange norėdami pranest jog perduodami duomenys iš vaikinio lango (perduodamas hashas)*/
var _fReturn = null;
/** Funkcija kurią kviesim senajame lange norėdami pranest jog langas užsikrovė*/
var _fOnChildLoad = null;
/** Funkcija kurią kviesim senajame lange norėdami pranest jog langas uždaromas*/
var _fOnChildUnload = null;
//---------------------------------------------------------------------
//--------------------------------------------------------------------------------------
/**
    Nustato reikšmę, kuria pasiims iškviestasis langas (tik FF).
    @param p_objArg Perduodami duomenys
    @param p_fRet funkcija kuri bus iškviečiama langui užsidarant
*/
function setVal(p_objArg, p_fRet, p_fOnLoad, p_fOnUnload)
{
	_val = p_objArg;
	_fReturn = p_fRet;
	_fOnChildLoad = p_fOnLoad;
	_fOnChildUnload = p_fOnUnload;
}

//--------------------------------------------------------------------------------------
try
{
    if(window.opener)
    {
        if(window.opener._fOnChildLoad != null)
        {
            addEvent(window, 'load', callParent);
        }    
        if(window.opener._fOnChildUnload != null)
            addEvent(window, 'unload', callParent);
    }
}
catch(exception){}
//--------------------------------------------------------------------------------------
function callParent(e)
{
    if(e.type == 'load' && window.opener._fOnChildLoad)
        window.opener._fOnChildLoad(window);
    if(e.type == 'unload' && window.opener._fOnChildUnload)
        window.opener._fOnChildUnload(window);
}
//--------------------------------------------------------------------------------------


/*
    Gražina reikšmę iš modalinio lango. Funkcija atskiria ar langas yra rėmelyje ar ne ir 
    galutinai iškviecia setRet funkcija viršutiniame lange arba lange, kuriame parametras blnMainWindow = true.
*/
function setRet(arg)
{
	var objMainWind = g_obj_fGetMainWindow();
	if (objMainWind && objMainWind != window)
	{
	    objMainWind.setRet(arg);
	}
	else
	{
	    try
	    {
		    window.opener._ret = arg;
		    if(window.opener._fReturn)
		        window.opener._fReturn(arg);
	    }
	    catch(ee)
	    {
		    window.returnValue = arg;
	    }
	}
}
//--------------------------------------------------------------------------------------
/**
    Pasiima reikšmė iš iškviečiančio lango. Funkcija atskiria ar iškviestasis langas yra rėmelyje ar ne ir 
    galutinai iškviečia getVal funkcija viršutiniame lange arba lange, kuriame parametras blnMainWindow = true.
*/
function getVal()
{
    var objMainWind = g_obj_fGetMainWindow();
	if (objMainWind && objMainWind != window)
	{
	    return objMainWind.getVal();
	}
    else
	{
	    try 
        {
	        return(window.opener._val);
	    }
	    catch (ee)
	    {
	        return(window.dialogArguments);
	    }
	}
}
//--------------------------------------------------------------------------------------
/**
    Suranda pagrindini langa, kuris turi parametra blnMainWindow lygu true.
*/
function g_obj_fGetMainWindow()
{
    var obj = window;
    if (obj.blnMainWindow) return obj;
    while (obj.parent != obj)
    {
        obj = obj.parent;
        if (obj.blnMainWindow) return obj;
    }
    return null;
}
//--------------------------------------------------------------------------------------
/**
    Suranda pagrindini langa, kurio tevas yra jis pats
*/
function g_obj_fGetSuperParentWindow()
{
    var obj = window;
    while (obj.parent != obj)
    {
        obj = obj.parent;
    }
    return obj;
}
//--------------------------------------------------------------------------------------
/**
    Universali uždarymo funkcija, jei langas turi tevą, tai uždaro tėvą, jei ne tai uždaro langa.
*/
function g_fSHClose()
{
    if (window.parent != window)
    {
        window.parent.g_fSHClose();
    }
    else
    {
        window.close();
    }
}
//--------------------------------------------------------------------------------------
/** 
    Atidaro modalinį dialogą. Aukštis ir plotis nurodomi pagal mozillą.
    @param p_strUrl dialogo turinio adresas
    @param p_intWidth  lango plotis
    @param p_intHeight lango aukstis
    @param p_strParams parametrai perduodami is tevinio lango dialogo langui
    @param p_strResizable parametras nusakantis ar galima keist lango išmatavimus
    @returns Grazina dialogo grąžinamus parametrus.
    @type hsh
*/
function openDialog(p_strUrl, p_intWidth, p_intHeight, p_strParams, p_strResizable)
{
    if ( cIE )
    {
         p_intWidth = p_intWidth + 5;
         p_intHeight = p_intHeight + 25;
    }
    if(p_strParams == null)
    {
        p_strParams = new Object();
        p_strParams['window'] = window;
    }
    if(p_strResizable == null)
    {
        p_strResizable = 'yes';
    }
    if(p_strResizable == true)
    {
        p_strResizable = 'yes';
    }
    if(p_strResizable == false)
    {
        p_strResizable = 'no';
    }
	if(cIE)
	{
		return (window.showModalDialog(p_strUrl, p_strParams, 'dialogWidth:' + p_intWidth + 'px; dialogHeight:' + p_intHeight + 'px; center:yes; status:no; help:no; resizable:' + p_strResizable + '; scroll:no;') );
	}
	else
	{
		try
		{
		    setVal(p_strParams);
		    netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite");
		    
		 // lango X  ir Y  
		    var intScreenX = parseInt(window.screenX);
		    var intScreenY = parseInt(window.screenY);
		 
		 // randamas top'inis window
            var objTemp = window;
            while(objTemp != window.top)
            {
                objTemp = objTemp.parent;                                                    
            }
            
         // window plotis ir aukstis  
            var intInnerHeight = objTemp.outerHeight;
		    var intInnerWidth = objTemp.outerWidth;
         
         // lango centras
            var intCenterLeft = parseInt(intScreenX);
            var intCenterTop = parseInt(intScreenY);
            intCenterLeft += parseInt(intInnerWidth/2);
            intCenterTop += parseInt(intInnerHeight/2);
         
         // window pasirodymo left ir top   
            var intLeft = intCenterLeft - parseInt(p_intWidth/2);
            var intTop = intCenterTop - parseInt(p_intHeight/2);
            var objWindow = window.open(p_strUrl, '_blank', 'left='+ intLeft + ',top=' + intTop + ',width=' + p_intWidth + ',height=' + p_intHeight + ',modal=yes,dialog=yes,resizable=' + p_strResizable);
			return(_ret);
		}
		catch(ee)
		{
			return(ee);
		}
	}
}
//---------------------------------------------------------------------
/**
    Atidaro nauja paprastą langą. Aukštis ir plotis nurodomi pagal mozillą.
    @param p_strUrl Puslapio adresas
    @param p_intWidth Lango plotis
    @param p_intHeight Lango aukštis
    @param p_intLeft Lango atstumas nuo ekrano kairės
    @param p_intTop Lango atstumas nuo ekrano viršaus
    @param p_strTarget puslapio target atributas (atidarant antrą puslapį su tu pačiu target atributu, naujasis atsidaro ant senojo)
    @param p_strResizable parodo ar vartotojas gal?s keisti naujo lango dydį (yes/no)
    @param p_fRet funkcija kuri bus kviečiama užsidarant langui
    @param p_fOnLoad funkcija kuri bus iškviečiama tėviniame lange kai vaikinis langas užsikraus (paduodamas window)
    @param p_fOnUnload funkcija kuri bus iškviečiama tėviniame lange kai vaikinis langas bus uždaromas (paduodamas window)
*/
function openWindow(p_strUrl, p_intWidth, p_intHeight, p_intLeft, p_intTop, p_strTarget, p_strResizable, p_hshData, p_fRet, p_fOnLoad, p_fOnUnload)
{
    if ( cIE )
    {
         p_intWidth = p_intWidth - 5;
         p_intHeight = p_intHeight - 3;
    }
        
	var strTarget = '_blank';
	var strResizab = 'yes';
	if(p_strTarget != null)
	    strTarget = p_strTarget;
	if(p_strResizable != null)
	    strResizab = p_strResizable;
	setVal(p_hshData, p_fRet, p_fOnLoad, p_fOnUnload);
	var objWindow = window.open(p_strUrl, strTarget, 'toolbar=no, location=no, directories=no, status=yes, menubar=no, scrollbars=0, resizable=' + strResizab + ', copyhistory=no, width=' + p_intWidth + ', height=' + p_intHeight + ',top=' + p_intTop + ',left=' + p_intLeft);
	return objWindow;
	
}
/** 
    Atidaromas objekto redagavimo formos su medžiu langas atitinkamame režime.
    @param p_strFile failo tipas ( 'user', 'securityRole', 'viewRole', 'server', ...)
    @param p_strType  atidaromo lango tipas( 'edit', 'new', 'read' )
    @param p_arr_strValue raktinių laukų reikšmių masyvas ( pvz 'Jonas2000', 13)
    @param p_arr_strKeys raktinių laukų masyvas (pvz [username],[id])
    @param p_strToolbarButtons įrankių juostos mygtukai ('save_saveClose_help')
    @param p_hshData pradinių duomenų hashas, jo key turi sutapt su db key
    @param p_objWindow paduodamas window kuriame bus užkraunama forma
    @param p_fRet funkcija kuri bus kviečiama uždarant formą (jei ne null, bus atidaroma NE-Modaliniame lange)
    @param p_strSizeType atidaromo lango dydžio tipas( pagal nutylėjimą 'normal' )
*/
function g_hsh_fOpenForm( p_strFile, p_strType, p_arr_strValue, p_arr_strKeys,  p_strToolbarButtons, p_hshData, p_objWindow, p_fRet, p_strSizeType )
{
    // DA ideta, nes negalima siu formu atidaryt new rezime
    if ( ((p_strFile == 'viewRole') || (p_strFile == 'securityRole')) && (p_strType == 'new'))
    {
        return null;
    }
    
    
    var hshParameters = new Object();
    hshParameters['strFileType'] =  p_strFile; 
    hshParameters['strType'] = p_strType;
    hshParameters['arr_strKeyValues'] = p_arr_strValue;
    if ( p_strToolbarButtons != null )
        hshParameters['strToolbarButtons'] = p_strToolbarButtons;
    else
        hshParameters['strToolbarButtons'] = 'save_saveClose_help';
    if ( p_arr_strKeys != null )
        hshParameters['arr_strKeyFields'] = p_arr_strKeys; 
        
    hshParameters['fOnSave'] = 'fAfterSave'; 
      
    var strPage = g_str_fOpenDialogWithTree( hshParameters );
    var hshData = new Object();
    var hshPar = new Object();
    hshPar['window'] = window;
    hshPar['data'] = p_hshData;  
    
    if ( p_strSizeType == null ) p_strSizeType = 'normal';    
    var hshSizes;
    if ( g_objDialogWithTreeSizes.g_hshSizes[p_strSizeType] != null )
    {
        hshSizes = g_objDialogWithTreeSizes.g_hshSizes[p_strSizeType]; 
    }
    else
    {
        hshSizes = g_objDialogWithTreeSizes.g_hshSizes['normal']; 
    }
      
    if(p_fRet == null)
        hshData = openDialog(strPage, hshSizes['intMozDialogWidth'], hshSizes['intMozDialogHeight'], hshPar, 'yes' )
    else
        openWindow(strPage, hshSizes['intMozWindowWidth'], hshSizes['intMozWindowHeight'], 100, 100, null, 'yes', hshPar, p_fRet); 
    return( hshData );
}
//-----------------------------------------------------------------------------------
// DA opens dialog with tree with some default parameters
/** 
    Atidaromas objekto redagavimo formos su medžiu langas atitinkamame režime paieškos rezultatams vaizduoti.
    @param p_strTable nagrinėjamos lentelės vardas
    @param p_arr_strKey raktinių laukų masyvas (pvz [username],[id])
    @param p_arr_strValue raktinių laukų reikšmių masyvas ( pvz 'Jonas2000', 13)    
    @param p_strPersonData nagrinėjamo asmens duomenys
    @param p_objWindow paduodamas window kuriame bus užkraunama forma   
    @param p_strSizeType atidaromo lango dydžio tipas( pagal nutylėjimą 'normal' )
*/
function g_hsh_fOpenWADialogWithTree( p_strTable, p_arr_strKey, p_arr_strValue, p_strPersonData, p_objWindow, p_strSizeType )
{  
    // atrenka pagal pirma raktini lauka. Jei reiktu daugiau, tektu modifikuoti faile frmWAResultDialog.aspx.cs
    // ir cia parametra 'key' ir jo sudedamas bei paimamas reiksmes strKey
    var strKey = p_arr_strKey[0];    
    var arr_strKey = new Array();
    for ( var i = 0; i < p_arr_strKey.length; i++ )
    {
        arr_strKey.push(p_arr_strKey[i]); 
    }     
    arr_strKey.push('table');
    arr_strKey.push('key');
   
    var arr_strValue = new Array();
    for ( var i = 0; i < p_arr_strValue.length; i++ )
    {
        arr_strValue.push(p_arr_strValue[i]); 
    } 
    
    arr_strValue.push(p_strTable);
    arr_strValue.push(strKey);    
    
    var hshParameters = new Object();
    hshParameters['strType'] = 'read';
    hshParameters['strStatus'] = 'read';
    hshParameters['arr_strKeyValues'] = arr_strValue;   
    hshParameters['strToolbarButtons'] = null;   
    
    if ( p_strTable != 'wbk' )
    {
        hshParameters['strFile'] = 'xmlWATree';
    }
    else
    {
        hshParameters['strFile'] = 'xmlWAWBKTree';
        hshParameters['blnDb'] = false; 
        hshParameters['strConn'] = 'WA_DATA';       
    }
    hshParameters['arr_strKeyFields'] = arr_strKey;   
    hshParameters['strLabelWord1'] = 'person_details'; 
    hshParameters['strTranslate'] = '1_1_0';
    if ( p_strPersonData != null )
    {
        hshParameters['strLabelWord2'] = p_strPersonData;
    }    

    var strPage = g_str_fOpenDialogWithTree( hshParameters );
    var hshData = new Object(); 
    
    if (  p_objWindow != null )
    {  
          p_objWindow.location.href = strPage;    
    }
    else
    {
         if ( p_strSizeType == null ) p_strSizeType = 'normal';    
         var hshSizes;
         if ( g_objDialogWithTreeSizes.g_hshSizes[p_strSizeType] != null )
         {
             hshSizes = g_objDialogWithTreeSizes.g_hshSizes[p_strSizeType]; 
         }
         else
         {
             hshSizes = g_objDialogWithTreeSizes.g_hshSizes['normal']; 
         }
    
         var hshPar = new Object();
         hshPar['window'] = window;
         hshData = openDialog(strPage, hshSizes['intMozDialogWidth'], hshSizes['intMozDialogHeight'], hshPar, 'no' );
        
        /*if ( cIE )
        {   
           var hshPar = new Object();
           hshPar['window'] = window; 
           hshData = openDialog( strPage, hshSizes['intIEDialogWidth'], hshSizes['intIEDialogHeight'], hshPar, 'no' );         
        }
        else
        {
           var hshPar = new Object();
           hshPar['window'] = window;
           hshData = openDialog(strPage, hshSizes['intMozDialogWidth'], hshSizes['intMozDialogHeight'], hshPar, 'no' );
        }*/
    }
    return hshData;
}


//-----------------------------------------------------------------
/**
    Metodas sukonstruoja atitinkamą URL pagal nurodytus parametrus.
    @param p_hshParameters parametrų hashas:<br>
    <pre>
     p_hshParameters['strFile'] - tree file
     p_hshParameters['strType'] - ( 'edit', 'new' )
     p_hshParameters['arr_strKeyFields'] - key fields
     p_hshParameters['arr_strKeyValues'] - key values
     p_hshParameters['strToolbarButtons'] - 'save_saveClose'
     p_hshParameters['strPage'] - page to open first
     p_hshParameters['strStatus'] - status value
     p_hshParameters['strLabelWord1'] - label value first word ( ex. 'User_surname, name') ( first word - 'User', second word - 'surname, name')
     p_hshParameters['strLabelWord2'] - label value second word
     p_hshParameters['strTranslate'] - 1-translate, 0 - not ( status, label first word(ex. user), label second word (ex. name, surname), ex.'1_1_0' 
     p_hshParameters['fOnSave'] - function that will be used if changes were saved correctly
 </pre>
    @returns sukonstruotą atitinkamą URL
    @type string
*/
function g_str_fOpenDialogWithTree( p_hshParameters )
{
    strValue = cSYS.cABS_VIRTUAL_PATH + 'frmDialogWithTree.aspx';
    if ( p_hshParameters != null )
    {
        strValue += '?';
        if ( p_hshParameters['strPage'] != null )
            strValue += 'page=' + p_hshParameters['strPage'];
            
        if ( p_hshParameters['strFileType'] != null  )
            strValue += '&fileType=' + p_hshParameters['strFileType'];
          
            
        if ( p_hshParameters['strToolbarButtons'] != null  )
            strValue += '&toolbar=' + p_hshParameters['strToolbarButtons'];
        else
            strValue += '&toolbar=' + 'save_saveClose_help';
            
        if ( p_hshParameters['fOnSave'] != null  )
            strValue += '&java=' + p_hshParameters['fOnSave'];
        
        if ( p_hshParameters['strStatus'] != null  )
            strValue += '&status=' + p_hshParameters['strStatus'];
        
        if ( p_hshParameters['strLabelWord1'] != null  )
        {
            strValue += '&path=' + p_hshParameters['strLabelWord1'];
            if ( p_hshParameters['strLabelWord2'] != null  )
                strValue += '&path2=' + encode(p_hshParameters['strLabelWord2']);
        }
        
        if ( p_hshParameters['strTranslate'] != null  )
            strValue += '&lang=' + p_hshParameters['strTranslate'];            
        
        if ( p_hshParameters['strFile'] != null  )
            strValue += '&file=' + p_hshParameters['strFile'];
               
        if ( p_hshParameters['strType'] != null  )
            strValue += '&type=' + p_hshParameters['strType'];
        
        if ( p_hshParameters['blnDb'] != null  )
            strValue += '&inDb=' + p_hshParameters['blnDb'];
        
        if ( p_hshParameters['strConn'] != null  )
            strValue += '&conn=' + p_hshParameters['strConn'];
        
        if ( (p_hshParameters['arr_strKeyFields'] != null ) && (p_hshParameters['arr_strKeyValues'] != null)  )
        {
            if ( (p_hshParameters['arr_strKeyFields'].length == p_hshParameters['arr_strKeyValues'].length) && (p_hshParameters['arr_strKeyFields'].length > 0) )
            {
                var strFields = '';
                for ( var i = 0; i < p_hshParameters['arr_strKeyFields'].length; i++ )
                {   
                    if ( i > 0 ) 
                        strFields += '&';
                    strFields += p_hshParameters['arr_strKeyFields'][i] + '=' + encode(p_hshParameters['arr_strKeyValues'][i]);
                }
                strValue += '&fields=' + encode(strFields);
            }           
        }      
    } 
    return( strValue );
} 
//-----------------------------------------------------------------
/**
    Atidaro printToolsa ataskaitos spausdinimo rėžime.
    @param p_strPrintPath printToolso url
    @param p_strDirectory spausdinimo šablono direktorija
    @param p_strFileName spausdinimo šablono failo vardas
    @param p_strParameters SQL sakinio WHERE dalis
    @param p_strConnectionString prisijungimas prie duomenų bazės
    @param p_strLang kalba, kuria užkrauti printToolsa
*/
function g_fOpenPrintTool( p_strPrintPath, p_strDirectory, p_strFileName, p_strParameters, p_strConnectionString, p_strLang )
{
    if ( (p_strPrintPath != null) && (p_strFileName != null) )
    {  
        var strPath = p_strPrintPath + 'print.aspx?fileName=' + encode(p_strFileName) + '&dir=' + p_strDirectory;
        //var strPath = cSYS.cABS_VIRTUAL_PATH + 'print.aspx?fileName=' + encode(p_strFileName) + '&dir=' + p_strDirectory;
        if (p_strConnectionString != null)
            strPath += '&connection=' + encode(p_strConnectionString);         
        if ((p_strParameters != null) && (p_strParameters != ''))
            strPath += '&parameter=' + encode(p_strParameters);         
        if (p_strLang != null)
            strPath += '&lang=' + encode(p_strLang);         
        var intWidth = window.screen.availWidth - 50;  
        var intHeight = window.screen.availHeight - 100; //console(strPath);
        openWindow(strPath, window.screen.availWidth - 10, window.screen.availHeight - 50, null, null, 'printWindow', 'yes'); 
    }
}
//-----------------------------------------------------------------
/**
    Atidaro printToolsa šablono redagavimo rėžime.
    @param p_strPrintPath printToolso url
    @param p_strDirectory spausdinimo šablono failo direktorija
    @param p_strFileName spausdinimo šablono failo vardas
    @param p_strLang sistemos naudojama kalba
*/
function g_fOpenPrintToolEdit( p_strPrintPath, p_strDirectory, p_strFileName, p_strLang)
{
    if ( ( p_strPrintPath != null ) && ( p_strFileName != null ) )
    { 
        var strPath = p_strPrintPath + 'Default.aspx?fileName=' + encode(p_strFileName) + '&dir=' + p_strDirectory;
        if (p_strLang != null)
        {
            strPath += '&lang=' + encode(p_strLang);         
        }
        var intWidth = window.screen.availWidth - 50;  
        var intHeight = window.screen.availHeight - 100;
        openWindow(strPath, window.screen.availWidth - 10, window.screen.availHeight - 50, null, null, 'printWindow', 'yes'); 
    }
}

/**
    Atidaro pagalbos sistemą ir užkrauna nurodytą pagalbos failą.
    @param p_strLang kalbos trumpinys kuria reikia užkrauti helpą
    @param p_strFilename pagalbos failo vardas
*/
function g_fOpenHelp(p_strLang, p_strFilename)
{
   openWindow(cHELP_TOOL_PATH + 'help.aspx?lang=' + p_strLang +'&path=' + cHELP_DIR + '&file=' + p_strFilename, 400, 600, 100, 100, 'helpCmcMain', 'yes');
}

var g_objDialogWithTreeSizes = new clsDialogWithTreeSizes();
/**
    DA laikina klasė, skirta paimti langų dydžiams
*/
function clsDialogWithTreeSizes()
{
    this.g_hshSizes = new Object();
    
    var hshTemp = new Object();
   /* hshTemp['intIEDialogWidth'] = 860;
    hshTemp['intIEDialogHeight'] = 550;
    hshTemp['intIEWindowWidth'] = 850;
    hshTemp['intIEWindowHeight'] = 520;*/
    hshTemp['intMozDialogWidth'] = 855;//860
    hshTemp['intMozDialogHeight'] = 523;
    hshTemp['intMozWindowWidth'] = 855;//860
    hshTemp['intMozWindowHeight'] = 526;
    hshTemp['intTabWidth'] = 675;
    hshTemp['intTabHeight'] = 385;
    this.g_hshSizes['normal'] = hshTemp;   
    
}


//---------------------------------------------------------------
function bcCacheSystem()
{
	var xmlCache = new Object();
	var objThis = this;
	//---------------------------------------------------------------
	
	//---------------------------------------------------------------
	function g_objFindParent()
	{
	    try
	    {
	        if(  window.parent != window && window.parent.cacheSystem != null)
	        {  
	            return( window.parent.cacheSystem);
	        }
	        else
	        if(window.opener != null && window.opener.cacheSystem != null)
	        {
	           return( window.opener.cacheSystem );
	        }
	        else
	        if(window.dialogArguments && window.dialogArguments['window'] != null && window.dialogArguments['window'].cacheSystem)
	        {
	             return( window.dialogArguments['window'].cacheSystem );
	        }
	        else
	        {
	             return(null);
	        }
	    }
	    catch(objExcep)
	    {
	        return(null);
	    }
	}
	//---------------------------------------------------------------
	this.g_fInsertXml = function(p_strFilename, p_objXml)
	{
	    var objParent = g_objFindParent();
	    if(objParent != null)
	    {
	        objParent.g_fInsertXml(p_strFilename, p_objXml);
		}
		else
		{
		    xmlCache[p_strFilename] = p_objXml;
		}
	}
	//---------------------------------------------------------------
	this.g_obj_fGetXml = function(p_strFilename)
	{
	    try
	    {
	        var objParent = g_objFindParent();
	        if(objParent != null)
	        {
	            return( objParent.g_obj_fGetXml(p_strFilename) );
	        }
	        else
	        {
	            return(xmlCache[p_strFilename]);
	        }
	    }
	    catch(Exception)
	    {
	        consoleA('is cacho...[klaida isimant is cacheSystem]');
	        return(null);
	    }
	}
	//---------------------------------------------------------------
}
var cacheSystem = new bcCacheSystem();

/**
    Iškviečia naują puslapį.    
*/
function g_fRedirectToPage(p_strPageUrl)
{
    window.location = cSYS.cABS_VIRTUAL_PATH + p_strPageUrl;
}

// Langų kvietimo funkcijos \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

//<><><>////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////                                                 ///////////////
////////////////             Spausdinimo funkcijos               ///////////////
////////////////                                                 ///////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

var g_strQuery = '';
var g_strDbString = null;
var g_fPrintingHandlerFunction = null;
/**
    Bendra funkcija skirta spausdinimui iš duomenų bazės užklausos
    @param p_strQuery  užklausos parametrai
    @param p_objParams  objektas, kuris gali tur4ti užsetintus šiuos kintamuosius:<br>
    <pre>
        'preset' - saugomas preset id ir name junginys per '_'.
        'presetId' - saugomas preset id.
        'viewId' - saugomas view id.
        Galima neužsetinti nei vieno, tada nebus galima redaguoti vaizdo šablonų.
    </pre>
    @param p_arr_hshBcPrintPresets  leidžiamų pasirinkti šablonu masyvas
    @param p_strTitle - Print dialogo pavadinimas. Neverciamas
    @param p_intWhich - kuria duomenų bazė naudoti, jei null arba 1, tai naudojama konfiguracijos db,
      kai 2, tai naudojama ginklu db.
*/
function g_fManagePrinting(p_strQuery, p_objParams, p_arr_hshBcPrintPresets, p_strTitle, p_strConnString, p_fFunction)
{
    g_strDBSelector = p_strConnString;
    g_strQuery = p_strQuery;
    g_fPrintingHandlerFunction = p_fFunction;
    g_objPrintDialog.g_fOpen(null, null, p_objParams, p_arr_hshBcPrintPresets , g_fCompletePrintingSelection, p_strTitle);          
}


//--------------------------------------------------------------------------------------
/**  
    Funkcija, kviečiama pasirinkus šabloną ir patvirtinus spausdinimą.
    @param p_hshAts duomenys reikalingi perduoti į printToolsą
*/
function g_fCompletePrintingSelection(p_hshAts)
{
    if (typeof (g_fPrintingHandlerFunction) == 'function')
        g_fPrintingHandlerFunction(p_hshAts);
    if (p_hshAts == null)
        return;
    var arr_strDalys = cCONN_STRINGS.split('*');
    var hshConnStrings = new Object();
    for(var i = 0;i < arr_strDalys.length;i++)
    {
        var arr_strDalysTemp = arr_strDalys[i].split('^');
        hshConnStrings['[' + arr_strDalysTemp[0] + ']'] = arr_strDalysTemp[1];
    }
    var strConnString = '';
    switch(g_strDBSelector)
    {
        case '[confCmcDbString]': strConnString = cCMC_CONN_STRING; break;
        case '[confWaffenDbString]': strConnString = cWAFFEN_CONN_STRING; break;
        case '[confLbfDbString]': strConnString = cLBF_CONN_STRING; break;
        default : strConnString = cCMC_CONN_STRING; break;
    }
    if(hshConnStrings[g_strDBSelector] != null)
        strConnString = hshConnStrings[g_strDBSelector];
    if(p_hshAts != null)
        g_fOpenPrintTool( cPRINT_TOOL_PATH, cREPORT_SAVE_DIR, p_hshAts['filename'], g_strQuery, strConnString, cSYS.cLANG);
}

// Spausdinimo funkcijos \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

//<><><>////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////                                                 ///////////////
////////////////                  Langų sistema                  ///////////////
////////////////                                                 ///////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

/**
    @class clsWindow
    Javascript lango klasė. 
    Javascript langas - tai absoliučiai pozicionuotas divas, kuriame įdedamas turinys išsiskiriantis iš kitų puslapio dalių.
    Langas turi tokias savybes:
        Modališkumas
        Nešiojamumas ir dydžio keitimas
        Pozicijos nustatymas - Langui galima nustatyti norimą poziciją arba leisti išsicentruoti.    
        Dydžio nustatymas - langui galima priskirti dydį arba leisti susitraukti iki turinio.      
    @param p_blnModal - ar langas modalinis.          
    @extends iEventInterface
*/
function clsWindow(p_blnModal)
{
    this.g_strId = g_str_fIdGenerator();
    // this.blnModal - šis kintamasis priskiriamas su g_fSetModal funkcija
    this.g_fSetModal(p_blnModal);
    this.intZ = 0;
    this.intLeft = '';
    this.intTop = '';   
    this.blnOpened = false;
    this.hshConstraints = {};
    this.blnAttached = false;
    this.fCreate();     
}
    
    /**
        Parodo langą.
    */
    clsWindow.prototype.g_fShow = function()
    {
        //alert('clsWindow.prototype.g_fShow');
        if (this.blnOpened)
            return;
        var intZ = clsWindowManager.g_int_fSetWindowOnTop(this);
        this.fApplyPosition();
        this.g_fSetZ(intZ);
        this.blnOpened = true;
        if (!this.blnAttached)
        {
            this.fAppendToDOM();
        }
        
    }    
    
    /**
        Paslepia langą.
    */
    clsWindow.prototype.g_fHide = function()
    {
        //console('clsWindow.prototype.g_fHide');
        if (!this.blnOpened)
            return;
        this.objMainElement.style.display = 'none';
        if (this.blnCurtainShown)
        {
            g_objCurtain.g_fHide();
            this.blnCurtainShown = false;
        }
        this.blnOpened = false;
        clsWindowManager.g_fWindowClose(this);
        
    } 
    
    /**
        Padaro langą nešiojamą pagriebus už p_objHeader elementą.
        @param p_objHeader - elementas ant kurio paspaudus bus pradėtas nešimas.
    */
    clsWindow.prototype.g_fMakeDraggable = function(p_objHeader)
    {
        if (typeof clsDraggable == 'function')
        {
            p_objHeader = g_obj_fElement(p_objHeader);
            p_objHeader.style.cursor = 'move';
            var objDrager = new clsDraggable(p_objHeader, 'window');
            objDrager.g_fAddEvent(cEvents.cDragStart, this, this.fDragStart);
            objDrager.g_fAddEvent(cEvents.cDrag, this, this.fDrag);
        }
    }
    
    /**
        Funkcija, padaranti langą nešiojamą patempus už bet kurios jo vietos.
    */
    clsWindow.prototype.g_fMakeAllDraggable = function()
    {
        this.g_fMakeDraggable(this.objMainElement);    
    }
    
    /**
        Padaro langą nešiojamą pagriebus už p_objHeader elementą.
        @param p_objHeader - elementas ant kurio paspaudus bus pradėtas resizinimas.
        @param p_strHorizontal - parodo kaip galima resizinti horizontaliai. Galimos reikšmės: 'left', 'right', 'none'.
        @param p_strVertical - parodo kaip galima resizinti vertikaliai. Galimos reikšmės: 'top', 'bottom', 'none'.   
    */
    clsWindow.prototype.g_fMakeResizable = function(p_objHeader, p_strHorizontal, p_strVertical)
    {
        if (typeof clsDraggable == 'function')
        {
            p_objHeader = g_obj_fElement(p_objHeader);
            //p_objHeader.style.cursor = 'move';
            var objResizer = new clsDraggable(p_objHeader, 'window_resize');
            objResizer.g_fSetValue('horizontal', p_strHorizontal);
            objResizer.g_fSetValue('vertical', p_strVertical);
            objResizer.g_fAddEvent(cEvents.cDragStart, this, this.fResizeStart);
            objResizer.g_fAddEvent(cEvents.cDrag, this, this.fResize);
            var strCursorStyle = '';
            if (p_strVertical == 'top')
                strCursorStyle += 'n';
            else if (p_strVertical == 'bottom')
                strCursorStyle += 's';    
            if (p_strHorizontal == 'left')
                strCursorStyle += 'w';
            else if (p_strHorizontal == 'right')
                strCursorStyle += 'e';
            if (strCursorStyle != '')              
                p_objHeader.style.cursor = strCursorStyle + '-resize';
        }
    }
    
    /**
        Nustatome lango plotį ir aukštį. Jei kuris nors iš šių parametrų yra null, tai tada 
        atitinkamas parametras nepakeičiamas, o jei '' tai nustatomas į ''.  
        @param p_objWidth - Plotis. Gali būti null, '', arba skaičius.
        @param p_objHeight - Aukštis. Gali būti null, '', arba skaičius.
    */
    clsWindow.prototype.g_fSetSize = function(p_objWidth, p_objHeight)
    {
        this.fCalculatePositionDiffs();
        if (p_objWidth != null)
        {
            if (p_objWidth === '')
                this.objSizeElement.style.width = '';
            else
                this.objSizeElement.style.width = (p_objWidth - this.intLeftDiff - this.intRightDiff) + 'px';
        }
        if (p_objHeight != null)
        {
            if (p_objHeight === '')
                this.objSizeElement.style.height = '';
            else
                this.objSizeElement.style.height = (p_objHeight - this.intRightDiff - this.intBottomDiff) + 'px';
        }
        
        
    }
    
    /**
        Nustatome lango poziciją nuo dokumento kairiojo viršutinio kampo.
        Pozicija nurodoma left ir top parametrais. Jei kuris nors iš šių parametrų yra null, tai tada 
        atitinkamas parametras nepakeičiamas, o jei '' tai pagal tą koordinatę yra centruojama matomame lange.
        Jei nurodomas skaičius, jis reiškia kiek lango kairysis viršutinis kampas yra nutolęs nuo dokumento atitinkamo taško.  
        @param p_objLeft - Plotis. Gali būti null, '', arba skaičius.
        @param p_objTop - Aukštis. Gali būti null, '', arba skaičius.
    */
    clsWindow.prototype.g_fSetPosition = function(p_objLeft, p_objTop)
    {
        if (p_objLeft != null)
        {
            this.intLeft = p_objLeft;
        }
        if (p_objTop != null)
        {
            this.intTop = p_objTop;
        }
        if (this.blnOpened)
            this.fApplyPosition();
    }
    
    /**
        Nustato lango apribojimus. Apribojimai galioja resizinant langą, bet visada 
        galima per funkciją g_fSetSize nustatyti norimą dydį.
        @param p_hshConstraints - apribojimų hashas su šiomis reikšmėmis:
            intMinWidth - mažiausias plotis
            intMaxWidth - didžiausias plotis
            intMinHeight - mažiausias aukštis
            intMaxHeight - didžiausias aukštis
    */
    clsWindow.prototype.g_fSetConstraints = function(p_hshConstraints)
    {
        if (p_hshConstraints && typeof (p_hshConstraints) == 'object')
        {
            this.hshConstraints = p_hshConstraints;
        }
    }
    
    /**
        Nustato ar langas yra modalinis. Priskyrus reikia paslėpti ir vėl parodyti langą, nes iš karto neatsinaujins.
        @param p_blnModal - Ar langas yra modalinis.
    */
    clsWindow.prototype.g_fSetModal = function(p_blnModal)
    {
        this.blnModal = !!p_blnModal;
    }
    
    /**
        Gauna lango indeksą.
        @type int
    */
    clsWindow.prototype.g_int_fGetZ = function()
    {
        return this.intZ;
    }
    
    /**
        Nustato lango Z indeksą.
        @param p_intZ - nauja zIndex reikšmė.
    */
    clsWindow.prototype.g_fSetZ = function(p_intZ)
    {
        //alert('clsWindow.prototype.g_fSetZ');
        this.intZ = p_intZ;
        this.objMainElement.style.zIndex = this.intZ;
        this.objMainElement.style.display = 'block';
        this.g_fActivate();
    }
    
    /**
        Veiksmai, kuriuos reiktų atlikti, jei virš einamojo lango užsidaro (ar galėjo užsidaryti) kitas langas.
    */
    clsWindow.prototype.g_fActivate = function()
    {
        //alert('clsWindow.prototype.g_fActivate');
        if (this.blnModal)
        {
            //console('g_fActivate is modal');
            //console(this.intZ);
            g_objCurtain.g_fShow(this.intZ - 1);
            this.blnCurtainShown = true;
        }
    }
    
    /**
        Gauna elementą, į kurį galima dėti lango turinį.
        @type element
    */
    clsWindow.prototype.g_obj_fGetContent = function()
    {
        return this.objMainElement;
    }
    
    // Pagalbinės funkcijos
    
    /**
        Atlieka aktyvavimą, kai yra paspaudžiama ant pasirinkto lango.
        @private
    */
    clsWindow.prototype.fActivateOnClick = function()
    {
        var intZ = clsWindowManager.g_int_fSetWindowOnTop(this);
        this.g_fSetZ(intZ);
    }
    
    /**
        Priskiriama pozicija. Turi būti vykdoma, kai jau žinomas this.objMainElement offset plotis,
        t.y. kai elementas yra parodomas.
        @private
    */
    clsWindow.prototype.fApplyPosition = function()
    {
        //alert('fApplyPosition');
        if (this.intLeft === '')
        {
            var intViewportStartX = document.documentElement.scrollLeft;
            var intViewportWidth = document.documentElement.clientWidth;
            var intWidth = this.objMainElement.offsetWidth;
            var intLeft = (intViewportWidth - intWidth) / 2;
            intLeft = intLeft < 0 ? 0 : intLeft;
            intLeft += intViewportStartX;
            this.objMainElement.style.left = intLeft + 'px';
        }
        else
        {
            this.objMainElement.style.left = this.intLeft + 'px';
        }
        
        if (this.intTop === '')
        {
            var intViewportStartY = document.documentElement.scrollTop;
            var intViewportHeight = document.documentElement.clientHeight;
            var intHeight = this.objMainElement.offsetHeight;
            var intTop = (intViewportHeight - intHeight) / 2;
            intTop = intTop < 0 ? 0 : intTop;
            intTop += intViewportStartY;
            this.objMainElement.style.top = intTop + 'px';
        }
        else
        {
            // Buvo absoliučiai, padaryta reliatyviai
            // this.objMainElement.style.top = this.intTop + 'px';
            this.objMainElement.style.top = (document.documentElement.scrollTop + this.intTop) + 'px';
        } 
    }
    
    /**
        Draginimo pradžios įvykis
        @param p_hshEvent Įvykio objektas.
        @private
    */
    clsWindow.prototype.fDragStart = function(p_hshEvent)
    {
        var objDraggable = p_hshEvent['object'];
        objDraggable.g_fSetBlock(this.objMainElement);
        // Draginimui reikalingi kintamieji
        this.intViewportStartX = document.documentElement.scrollLeft;
        this.intViewportStartY = document.documentElement.scrollTop;
        this.intViewportEndX = document.documentElement.clientWidth + this.intViewportStartX;
        this.intViewportEndY = document.documentElement.clientHeight + this.intViewportStartY;
        this.intContentWidth = document.documentElement.scrollWidth;
        this.intContentHeight = document.documentElement.scrollHeight;
        this.arr_intDiff = g_arr_int_fMakeRelative(g_arr_int_fPosition(p_hshEvent.object.objDragHandle), this.objMainElement);
        var objHandle = p_hshEvent.object.objDragHandle;
        this.intHandleWidth = objHandle.offsetWidth;
        this.intHandleHeight = objHandle.offsetHeight;
        this.intBlockWidth = this.objMainElement.offsetWidth;
        this.intBlockHeight = this.objMainElement.offsetHeight;
        
    }
    
    /**
        Draginimas, vykdomas ant mousemove įvykio, todėl čia reikia atlikinėti kuo mažiau veiksmų.
        @param p_hshEvent Įvykio objektas.
        @private
    */
    clsWindow.prototype.fDrag = function(p_hshEvent)
    {
        var intLeft = p_hshEvent['X'] + p_hshEvent['hshHandleOffset']['intXStartDiff'];
        if (intLeft + this.intHandleWidth > this.intViewportEndX)
            intLeft = this.intViewportEndX - this.intHandleWidth;
        intLeft = intLeft > this.intViewportStartX ? intLeft : this.intViewportStartX;
        intLeft -= this.arr_intDiff[0];
        if (intLeft + this.intBlockWidth > this.intContentWidth)
            intLeft = this.intContentWidth - this.intBlockWidth;
        intLeft = intLeft < 0 ? 0 : intLeft;
        
        var intTop = p_hshEvent['Y'] + p_hshEvent['hshHandleOffset']['intYStartDiff'];
        if (intTop + this.intHandleHeight > this.intViewportEndY)
            intTop = this.intViewportEndY - this.intHandleHeight;
        intTop = intTop > this.intViewportStartY ? intTop : this.intViewportStartY;
        intTop -= this.arr_intDiff[1];
        if (intTop + this.intBlockHeight > this.intContentHeight)
            intTop = this.intContentHeight - this.intBlockHeight;
        intTop = intTop < 0 ? 0 : intTop;
            
        this.objMainElement.style.left = intLeft + 'px';
        this.objMainElement.style.top = intTop + 'px';   
    }
    
    /**
        Dydžio keitimo pradžios įvykis
        @param p_hshEvent Įvykio objektas.
        @private
    */
    clsWindow.prototype.fResizeStart = function(p_hshEvent)
    {
        var objResizer = p_hshEvent['object'];
        this.strHorizontal = objResizer.g_obj_fGetValue('horizontal');
        this.strVertical = objResizer.g_obj_fGetValue('vertical');
        this.intViewportStartX = document.documentElement.scrollLeft;
        this.intViewportStartY = document.documentElement.scrollTop;
        this.intViewportEndX = document.documentElement.clientWidth + this.intViewportStartX;
        this.intViewportEndY = document.documentElement.clientHeight + this.intViewportStartY;
        this.fCalculatePositionDiffs();
    }
    
    /**
        Resizinimas, vykdomas ant mousemove įvykio, todėl čia reikia atlikinėti kuo mažiau veiksmų.
        @param p_hshEvent Įvykio objektas.
        @private
    */
    clsWindow.prototype.fResize = function(p_hshEvent)
    {
        if (this.strHorizontal == 'right')
        {
            var intWidth = this.arr_intMainPos[2] - p_hshEvent.firstLocalCoords.X + p_hshEvent.X;
            if (this.arr_intMainPos[0] + intWidth > this.intViewportEndX)
                intWidth = this.intViewportEndX - this.arr_intMainPos[0];
            if (this.hshConstraints['intMaxWidth'] && intWidth > this.hshConstraints['intMaxWidth'])
                intWidth = this.hshConstraints['intMaxWidth'];
            var intMinWidth = 20;
            if (this.hshConstraints['intMinWidth'])
                intMinWidth = this.hshConstraints['intMinWidth'];
            if (intWidth < intMinWidth)    
                intWidth = intMinWidth;
            this.objSizeElement.style.width = (intWidth - this.intLeftDiff - this.intRightDiff) + 'px';
        }
        else if (this.strHorizontal == 'left')
        {
            var intWindowEndX = this.objMainElement.offsetLeft + this.objMainElement.offsetWidth;
            var intLeft = this.arr_intMainPos[0] - p_hshEvent.firstLocalCoords.X + p_hshEvent.X;
            if (intLeft < this.intViewportStartX)
            {
                intLeft = this.intViewportStartX;
            }
            var intWidth = intWindowEndX - intLeft;
            if (this.hshConstraints['intMaxWidth'] && intWidth > this.hshConstraints['intMaxWidth'])
            {
                intLeft = intWindowEndX - this.hshConstraints['intMaxWidth'];
            }
            
            var intMinWidth = 20;
            if (this.hshConstraints['intMinWidth'])
                intMinWidth = this.hshConstraints['intMinWidth'];
            if (intLeft > intWindowEndX - intMinWidth)
            {
                intLeft = intWindowEndX - intMinWidth;
            }
            intWidth = intWindowEndX - intLeft;
            
            this.objMainElement.style.left = intLeft + 'px';
            this.objSizeElement.style.width = (intWidth - this.intLeftDiff - this.intRightDiff) + 'px';
        }
        
        if (this.strVertical == 'bottom')
        {
            var intHeight = this.arr_intMainPos[3] - p_hshEvent.firstLocalCoords.Y + p_hshEvent.Y;
            if (this.arr_intMainPos[1] + intHeight > this.intViewportEndY)
                intHeight = this.intViewportEndY - this.arr_intMainPos[1];
            if (this.hshConstraints['intMaxHeight'] && intHeight > this.hshConstraints['intMaxHeight'])
                intHeight = this.hshConstraints['intMaxHeight'];
            var intMinHeight = 20;
            if (this.hshConstraints['intMinHeight'])
                intMinHeight = this.hshConstraints['intMinHeight'];
            if (intHeight < intMinHeight)    
                intHeight = intMinHeight;
            this.objSizeElement.style.height = (intHeight - this.intTopDiff - this.intBottomDiff) + 'px';
        }
        else if (this.strVertical == 'top')
        {
            var intWindowEndY = this.objMainElement.offsetTop + this.objMainElement.offsetHeight;
            var intTop = this.arr_intMainPos[1] - p_hshEvent.firstLocalCoords.Y + p_hshEvent.Y;
            if (intTop < this.intViewportStartY)
            {
                intTop = this.intViewportStartY;
            }
            var intHeight = intWindowEndY - intTop;
            if (this.hshConstraints['intMaxHeight'] && intHeight > this.hshConstraints['intMaxHeight'])
            {
                intTop = intWindowEndY - this.hshConstraints['intMaxHeight'];
            }
            
            var intMinHeight = 20;
            if (this.hshConstraints['intMinHeight'])
                intMinHeight = this.hshConstraints['intMinHeight'];
            if (intTop > intWindowEndY - intMinHeight)
            {
                intTop = intWindowEndY - intMinHeight;
            }
            intHeight = intWindowEndY - intTop;
            
            this.objMainElement.style.top = intTop + 'px';
            this.objSizeElement.style.height = (intHeight - this.intTopDiff - this.intBottomDiff) + 'px';
        }
    }
    
    /**
        Lango elemento sukūrimas.
        @private
    */
    clsWindow.prototype.fCreate = function()
    {
        //alert('clsWindow.prototype.fCreate');
        this.objMainElement = document.createElement('DIV');
        this.objMainElement.id = this.g_strId;
        this.objSizeElement = this.objMainElement;
        var objStyle = this.objMainElement.style;
        objStyle.display = 'none';
        objStyle.position = 'absolute';
        objStyle.left = '0px';
        objStyle.top = '0px';
        
        if (document.body)
        {
            this.fAppendToDOM();
        }
    }
    //------------------------------------------------------------
    
    /**
        Lango div elemento pridėjimas į DOM. Reikalingas, nes ne visada iš karto sukūrus divą galime dėti į DOM medį.
        @private
    */
    clsWindow.prototype.fAppendToDOM = function()
    {
        //alert('clsWindow.prototype.fAppendToDOM');
//        var objParent = document.getElementById('content');
//        if (!objParent)
//            objParent = document.body;     
//        objParent.appendChild(this.objMainElement);
        document.body.appendChild(this.objMainElement);
        addEvent(this.objMainElement, 'mousedown', this.fActivateOnClick, this);
        this.blnAttached = true;
    }
    
    clsWindow.prototype.fCalculatePositionDiffs = function()
    {
        this.arr_intMainPos = g_arr_int_fPosition(this.objMainElement);
        this.arr_intSizePos = g_arr_int_fPosition(this.objSizeElement);
        this.intLeftDiff = this.arr_intSizePos[0] - this.arr_intMainPos[0];
        this.intTopDiff = this.arr_intSizePos[1] - this.arr_intMainPos[1];
        this.intRightDiff = this.arr_intMainPos[0] + this.arr_intMainPos[2] - this.arr_intSizePos[0] - this.arr_intSizePos[2];
        this.intBottomDiff = this.arr_intMainPos[1] + this.arr_intMainPos[3] - this.arr_intSizePos[1] - this.arr_intSizePos[3];
        //console(this.arr_intMainPos);
        //console(this.arr_intSizePos);
        //console(this.intLeftDiff + ' ' + this.intTopDiff + ' ' + this.intRightDiff + ' ' + this.intBottomDiff);
    }

/**
    @class clsWindowManager
    Tvarko kelių langų rodymą ir tarpusavio santykį.
    @static
*/   
var clsWindowManager = {
    hshWindows: new clsIndexedHash(),
    intMaxZ: 0
    
};
    
    /**
        Nurodyto lango iškėlimas virš kitų langų.
        @param p_objWindow - langas, kuriam suranda Z indeksą, kuris būna didžiausias tarp visų matomų langų, 
        kurie yra tvarkomi per šią klasę.
        @type int
    */   
    clsWindowManager.g_int_fSetWindowOnTop = function(p_objWindow)
    {
        if (this.hshWindows.g_bln_fIsLast(p_objWindow))
            return this.intMaxZ; //Nieko nereikia daryti, nes langas ir taip yra ant viršaus.
        if (this.hshWindows.g_fIsIn(p_objWindow))
        {
            this.hshWindows.g_obj_fRemove(p_objWindow);
        }
        var objTopWindow = this.hshWindows.g_obj_fGetLast();
        if (objTopWindow)
            this.intMaxZ = objTopWindow.g_int_fGetZ();
        else
            this.intMaxZ = 0;
        var intLength = this.hshWindows.g_int_fGetCount();
        this.hshWindows.g_str_fAdd(p_objWindow, intLength, p_objWindow.g_strId);
        this.intMaxZ += 2;
        p_objWindow.g_fSetZ(this.intMaxZ);      
        return this.intMaxZ; 
    }
    
    /**
        Lango uždarymas
        @param p_objWindow - langas, kurį reikia uždaryti.
    */
    clsWindowManager.g_fWindowClose = function(p_objWindow)
    {
        //console('clsWindowManager.g_fWindowClose');
        if (this.hshWindows.g_bln_fIsLast(p_objWindow))
        {
            //console('Is last');
            var objSecondTopWindow = this.hshWindows.g_obj_fGetPrevious(p_objWindow);
            if (objSecondTopWindow)
                objSecondTopWindow.g_fActivate();
        }
        this.hshWindows.g_obj_fRemove(p_objWindow);
    }    
    
/**
    @class g_objCurtain
    Modalinių langų uždangos klasė.
    @static
*/     
var g_objCurtain = {};    
g_objCurtain.blnCreated = false;
g_objCurtain.blnWasResized = false;
    
    /**
        Užsklandos parodymas
        @param p_intZIndex rodomos uždangos ZIndex reikšmė.
    */
    g_objCurtain.g_fShow = function(p_intZIndex)
    {
        //alert('g_objCurtain.g_fShow');
        this.fCreate();
        if (this.objMainElement.parentNode != document.body)
            document.body.appendChild(this.objMainElement);
        this.objMainElement.style.zIndex = p_intZIndex;
        this.fOnResize();
        addEvent(window, 'resize', this.fOnResize, this);
    }
    //------------------------------------------------------------
    
    /**
        Užsklandos paslėpimas
    */
    g_objCurtain.g_fHide = function()
    {
        //this.objMainElement.style.display = 'none';
        this.objMainElement.parentNode.removeChild(this.objMainElement);
        this.blnWasResized = true;
        removeEvent(window, 'resize', this.fOnResize, this);
    }
    //------------------------------------------------------------
    
    /**
        Užsklandos sukūrimas
        @private
    */
    g_objCurtain.fCreate = function()
    {
        if (this.blnCreated)
            return;   
        this.objMainElement = document.createElement('DIV');
        this.objMainElement.className = 'curtain';
        var objStyle = this.objMainElement.style;
        if (cIE) // Čia kad paskui nemėtytų css stiliaus klaidų kitos naršyklės
            g_fAddStyle('.curtain', 'filter: alpha(opacity=40);');
        objStyle.display = 'none';
        objStyle.position = 'absolute';
        objStyle.top = '0px';
        objStyle.left = '0px';
        document.body.appendChild(this.objMainElement);
        this.blnCreated = true;
        
    }
    //------------------------------------------------------------
    
//    /**
//        Užsklandos dydžio pakeitimas.
//        @private
//    */
//    g_objCurtain.fOnResize = function()
//    {
//        console('g_objCurtain.fOnResize');
//        for (var i = 0; i < 200; i++)
//            console(i);
//        //removeEvent(window, 'resize', this.fOnResize, this);
//        var objParentNode = document.documentElement;
//        if (!this.blnWasResized)
//        {
//            if (cFF)
//            {
//                this.intFirstWidth = window.innerWidth;    
//                this.intFirstHeight = window.innerHeight;
//            }
//            if (cIE)
//            {
//                this.intFirstWidth = document.body.offsetWidth;    
//                this.intFirstHeight = document.body.offsetHeight;
//            }
//            //console(objParentNode);
//            console('Pirmas aukštis: ' + this.intFirstHeight);
//            //this.blnWasHasHorizontal = objParentNode.clientWidth < objParentNode.scrollWidth;
//            //this.i = 0;
//        }
////        console(window.innerHeight);
////        console(window.innerWidth);
//        console('---');
//        //console(this.i++);
//        //console(objParentNode);
//        this.blnWasResized = true;
//        var intWidth = objParentNode.scrollLeft + objParentNode.clientWidth;
//        var intClientHeight = objParentNode.clientHeight;
//        console("Tėvo aukštis: " + intClientHeight);
//        if (cFF)
//            intClientHeight = Math.max(objParentNode.offsetHeight, intClientHeight);
//        var intHeight = objParentNode.scrollTop + intClientHeight;//Math.max(objParentNode.offsetHeight, objParentNode.clientHeight);
//        console('Vaiko aukštis: ' + intHeight);
//        intHeight = Math.max(intHeight, this.intFirstHeight);
//        console('Galutinis aukštis: ' + intHeight);
//        //this.blnHasHorizontal = objParentNode.clientWidth < objParentNode.scrollWidth;
//        //console(this.blnWasHasHorizontal);
//        //console(this.blnHasHorizontal);
//        
//        if (intWidth > this.intFirstWidth)
//        {
//            if (cIE7)// && this.blnWasHasHorizontal && !this.blnHasHorizontal)
//                intHeight += 16; 
//        }
//        else
//        {
//            intWidth = this.intFirstWidth;
//        }
//        // Nustatom plotį
//        this.objMainElement.style.width = intWidth + 'px';
//        // Nustatom aukštį
//        this.objMainElement.style.height = intHeight + 'px';     
//        
//        // Vėl parodom uždangą
//        this.objMainElement.style.display = 'block';
////        if (cFF)
////        {
////            var intWidth2 = objParentNode.scrollLeft + objParentNode.clientWidth;
////            var intHeight2 = objParentNode.scrollTop + objParentNode.clientHeight;
////            intWidth2 = Math.max(intWidth2, this.intFirstWidth);
////            intHeight2 = Math.max(intHeight2, this.intFirstHeight);
////            
////            if (intWidth2 > intWidth)
////            {
////                // Vėl nustatom plotį
////                this.objMainElement.style.width = intWidth2 + 'px';
////            }
////            if (intHeight2 > intHeight)
////            {
////                // Vėl nustatom aukštį
////                this.objMainElement.style.height = intHeight2 + 'px';
////            }
////        }
//        //this.blnWasHasHorizontal = this.blnHasHorizontal;
//        //addEvent(window, 'resize', this.fOnResize, this);
//    }
//    //------------------------------------------------------------
//    
    
    /**
        Užsklandos dydžio pakeitimas.
        @private
    */
    g_objCurtain.fOnResize = function()
    {
        //console('g_objCurtain.fOnResize');
        //removeEvent(window, 'resize', this.fOnResize, this);
        var objParentNode = document.documentElement;
        if (!this.blnWasResized)
        {
            this.intFirstWidth = objParentNode.scrollWidth;    
            this.intFirstHeight = objParentNode.scrollHeight;
//            console(objParentNode);
//            console('Pirmas aukštis: ' + this.intFirstHeight);
            //this.blnWasHasHorizontal = objParentNode.clientWidth < objParentNode.scrollWidth;
            //this.i = 0;
        }
        //console(window.innerHeight);
        //console(window.innerWidth);
        //console('---');
        //console(this.i++);
        //console(objParentNode);
        this.blnWasResized = true;
        var intWidth = objParentNode.scrollLeft + objParentNode.clientWidth;
        var intClientHeight = objParentNode.clientHeight;
//        console("Tėvo aukštis: " + intClientHeight);
//        if (cFF)
//            intClientHeight = Math.max(objParentNode.offsetHeight, intClientHeight);
        var intHeight = objParentNode.scrollTop + intClientHeight;//Math.max(objParentNode.offsetHeight, objParentNode.clientHeight);
//        console('Vaiko aukštis: ' + intHeight);
        intHeight = Math.max(intHeight, this.intFirstHeight);
//        console('Galutinis aukštis: ' + intHeight);
        //this.blnHasHorizontal = objParentNode.clientWidth < objParentNode.scrollWidth;
        //console(this.blnWasHasHorizontal);
        //console(this.blnHasHorizontal);
        
        if (intWidth > this.intFirstWidth)
        {
            if (cIE7)// && this.blnWasHasHorizontal && !this.blnHasHorizontal)
                intHeight += 16; 
            
        }
        else
        {
            intWidth = this.intFirstWidth;
        }
        // Nustatom plotį
        this.objMainElement.style.width = intWidth + 'px';
        // Nustatom aukštį
        this.objMainElement.style.height = intHeight + 'px';     
        
        // Vėl parodom uždangą
        this.objMainElement.style.display = 'block';
//        if (cFF)
//        {
//            var intWidth2 = objParentNode.scrollLeft + objParentNode.clientWidth;
//            var intHeight2 = objParentNode.scrollTop + objParentNode.clientHeight;
//            intWidth2 = Math.max(intWidth2, this.intFirstWidth);
//            intHeight2 = Math.max(intHeight2, this.intFirstHeight);
//            
//            if (intWidth2 > intWidth)
//            {
//                // Vėl nustatom plotį
//                this.objMainElement.style.width = intWidth2 + 'px';
//            }
//            if (intHeight2 > intHeight)
//            {
//                // Vėl nustatom aukštį
//                this.objMainElement.style.height = intHeight2 + 'px';
//            }
//        }
        //this.blnWasHasHorizontal = this.blnHasHorizontal;
        //addEvent(window, 'resize', this.fOnResize, this);
    }
    //------------------------------------------------------------
    

// Langų sistema \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

//<><><>////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////                                                 ///////////////
////////////////                     Konsolė                     ///////////////
////////////////                                                 ///////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////


/**
    Klasė skirta string eilučių rašymui į konsolės langelį.
    Reikia labai tobulinti, bet konsolė yra labai gera visokių focus įvykių sekimui, 
    kai negalima prarasti focuso iš elemento.
    @author Kęstutis Malinauskas
    @version 2 2007.12.06
    @extends clsWindow
    @constructor
*/
function clsConsole()
{
    clsConsole.baseConstructor.call(this, false);
    
    this.intMaxSimbolCount = 200000;
    this.intDepth = 8;
    this.blnShowFunctions = false;
    this.blnMinimized = false;
    this.blnCanOpen = true;
    this.blnConstructed = false;
}    

g_fExtend(clsConsole, clsWindow);

    clsConsole.prototype.g_fShow = function()
    {
        //alert('clsConsole start g_fShow method');
        if(!this.blnCanOpen)
            return;
        if(!this.blnOpened)
            this.g_fSetPosition(g_fGetViewportWidth() - 220, 20);
        if (!this.blnConstructed)
            this.fCreateConsole();
        // Pilnai perrašom tėvinį metodą g_fShow, nes mums reikia, kad Z indeksas būtų fiksuotas ir didelis
        if (!this.blnAttached)
        {
            //alert('Console fAppendToDOM');
            this.fAppendToDOM();
        }
        if (this.blnOpened)
            return;
        var intZ = 2000;//clsWindowManager.g_int_fSetWindowOnTop(this);
        this.fApplyPosition();
        this.g_fSetZ(intZ);
        this.blnOpened = true;
        //alert('clsConsole end g_fShow method');
    }
    
    clsConsole.prototype.g_fSetShowFunctions = function(p_blnValue)
    {
        this.blnShowFunctions = p_blnValue;
    }
    
    clsConsole.prototype.g_bln_fGetShowFunctions = function()
    {
        return this.blnShowFunctions;
    }
    
    clsConsole.prototype.g_fPrintLine = function(p_objItem)
    {
        var strAlert = this.str_fConstruct(p_objItem, 1, '');
        if (typeof(strAlert) != typeof(p_objItem) || strAlert != p_objItem) // KM 07.06.26 ant IE mesdavo klaidą, kai p_objItem būdavo XML nodas
        {
            strAlert = '<pre>' + strAlert + '</pre>';
        }
        this.g_fShow();
        if (this.objDiv)
        {
            this.fInsertText(this.objDiv, strAlert);
            this.objDiv.parentNode.scrollTop = this.objDiv.scrollHeight;
        }       
    }
    
    clsConsole.prototype.g_fUninit = function()
    {
        this.blnCanOpen = false;
//        if (this.objCopyImg)
//            removeEvent(this.objCopyImg, 'click', this.fCopy, this);
        if (this.objMinimizeImg)
            removeEvent(this.objMinimizeImg, 'click', this.fMinimize, this);
        this.objMinimizeImg = null;
        if (this.objMaximizeImg)
            removeEvent(this.objMaximizeImg, 'click', this.fMaximize, this);
        this.objMaximizeImg = null;
        if (this.objCloseImg)
            removeEvent(this.objCloseImg, 'click', this.fClose, this);
        this.objCloseImg = null;
        if (this.objClosePermImg)
            removeEvent(this.objClosePermImg, 'click', this.fClosePerm, this);
        this.objClosePermImg = null;  
        this.objContentRow = null;
        this.objFooterRow = null;
        this.objDiv = null;
        this.blnConstructed = false;  
    }
    
    clsConsole.prototype.g_str_fConstruct = function (p_objItem)
    {
       return this.str_fConstruct(p_objItem, 1, '') ;
    }
    
    clsConsole.prototype.g_fSetLevel = function(p_intLevel)
    {
        if (p_intLevel != null)
        {
            this.intDepth = p_intLevel;
        }    
    }
    
    //-----------------------------------------------
    /**
        Šią funkciją reikia perrašyti tam, kad konsolę galutinai atjungtume nuo bendros
        langų sistemos.
    */
    clsConsole.prototype.fActivateOnClick = function()
    {
        //Čia praktiškai nieko nereikia daryti
    }
    
    /**
        Rekursinė funkcija naudojama spaudinti elemento vaikus.
        @param p_objItem - tėvinis elementas kurio vaikus nagrin?jame.
        @param p_intLevel - šiuo metu esantis nagrinėjimo lygis.
        @param p_strPad - paddingo eilutė šiam lygiui.
        @returns Sukonstruotą HTML eilutę, vaizduojančią objekto struktūrą.
        @type string
    */
    clsConsole.prototype.str_fConstruct = function(p_objItem, p_intLevel, p_strPad)
    {
        var strNewPad = p_strPad + '    ';
        if(p_intLevel == this.intDepth)
            return('');
        var strAts = '';
        var strType = ftypeof(p_objItem);
        //strAts += strType + '\n';
        
        switch(strType)
        {
            case 'jsobject': for(strKey in p_objItem)
                        {
                            var strChildType = ftypeof(p_objItem[strKey]);
                            if( strKey == ('g_objParent') && strChildType == 'jsobject')
                            {
                                strAts += '\n' + p_strPad + '[\'' + strKey + '\']: ' + '[...]';
                            }
                            else
                            if(strChildType != 'function' || this.blnShowFunctions)
                            {
                                //strAts += '\n' + strChildType;
                                strAts += '\n' + p_strPad + '[\'' + strKey + '\']:  ' + this.str_fConstruct(p_objItem[strKey], p_intLevel + 1, strNewPad);
                            }
                        }
                        break;
                        
            case 'array': 
                        strAts += 'Array:';
//                        for(var intKey in p_objItem)
//                        {
//                            if (g_bln_fIsInt(intKey) && typeof (p_objItem[intKey]) != 'undefined')
//                                strAts += '\n' + p_strPad + '[' + intKey + ']: ' + str_fConstruct(p_objItem[intKey], p_intLevel + 1, strNewPad);
//                        }
                        for(var i = 0, intLength = p_objItem.length; i < intLength; i++)
                        {
                            if (typeof (p_objItem[i]) != 'undefined')
                                strAts += '\n' + p_strPad + '[' + i + ']: ' + this.str_fConstruct(p_objItem[i], p_intLevel + 1, strNewPad);
                        }
                        break;
            case 'domelement': strAts += 'DOM Element:' + this.str_fConstructDom(p_objItem, p_intLevel, p_strPad);
                        
                      break;
            case 'event': strAts += 'DOM Event:' + this.str_fConstructEvent(p_objItem, p_intLevel, p_strPad);
            
                      break;
            case 'function': if (this.blnShowFunctions) strAts += 'function(){...}';
                      break;          
            default : 
                if (p_objItem)
                {
                    if (p_objItem.replace) //Jei čia buvo stringas
                    {
                        strAts += p_objItem.replace(/>/g, '&gt;').replace(/</g, '&lt;'); 
                    }
                    else
                    {   
                        strAts += p_objItem.toString();    
                    }
                }
                else
                {
                    strAts += p_objItem;
                }
                break;
        }
        return(strAts);
    }
    
    clsConsole.prototype.str_fConstructEvent = function(p_objItem, p_intLevel, p_strPad)
    {
        var strNewPad = p_strPad + '    ';
        var strResult = '';
        p_strPad = strNewPad;
        strResult += '\n' + p_strPad + 'type: ' + p_objItem.type;
        strResult += '\n' + p_strPad + 'clientX: ' + p_objItem.clientX;
        strResult += '\n' + p_strPad + 'clientY: ' + p_objItem.clientY;
        strResult += '\n' + p_strPad + 'screenX: ' + p_objItem.screenX;
        strResult += '\n' + p_strPad + 'screenY: ' + p_objItem.screenY;
        strResult += '\n' + p_strPad + 'offsetX: ' + p_objItem.offsetX;
        strResult += '\n' + p_strPad + 'offsetY: ' + p_objItem.offsetY;
        strResult += '\n' + p_strPad + 'layerX: ' + p_objItem.layerX;
        strResult += '\n' + p_strPad + 'layerY: ' + p_objItem.layerY;
        strResult += '\n' + p_strPad + 'pageX: ' + p_objItem.pageX;
        strResult += '\n' + p_strPad + 'pageY: ' + p_objItem.pageY;
        strResult += '\n' + p_strPad + 'x: ' + p_objItem.x;
        strResult += '\n' + p_strPad + 'y: ' + p_objItem.y;
        strResult += '\n' + p_strPad + 'button: ' + p_objItem.button;
        strResult += '\n' + p_strPad + 'keyCode: ' + p_objItem.keyCode;
        strResult += '\n' + p_strPad + 'charCode: ' + p_objItem.charCode;
        strResult += '\n' + p_strPad + 'which: ' + p_objItem.which;
        strResult += '\n' + p_strPad + 'altKey: ' + p_objItem.altKey;
        strResult += '\n' + p_strPad + 'ctrlKey: ' + p_objItem.ctrlKey;
        strResult += '\n' + p_strPad + 'shiftKey: ' + p_objItem.shiftKey;
        strResult += '\n' + p_strPad + 'metaKey: ' + p_objItem.metaKey;
        strResult += '\n' + p_strPad + 'cancelBubble: ' + p_objItem.cancelBubble;
        strResult += '\n' + p_strPad + 'bubbles: ' + p_objItem.bubbles;
        strResult += '\n' + p_strPad + 'cancelable: ' + p_objItem.cancelable;
        strResult += '\n' + p_strPad + 'eventPhase: ' + p_objItem.eventPhase;
        strResult += '\n' + p_strPad + 'returnValue: ' + p_objItem.returnValue;
        strResult += '\n' + p_strPad + 'reason: ' + p_objItem.reason;
        strResult += '\n' + p_strPad + 'timestamp: ' + p_objItem.timestamp;
        strResult += '\n' + p_strPad + 'srcElement: ' + this.str_fConstruct(p_objItem.srcElement, p_intLevel + 1, strNewPad);   
        strResult += '\n' + p_strPad + 'currentTarget: ' + this.str_fConstruct(p_objItem.currentTarget, p_intLevel + 1, strNewPad);   
        strResult += '\n' + p_strPad + 'relatedTarget: ' + this.str_fConstruct(p_objItem.relatedTarget, p_intLevel + 1, strNewPad);   
        strResult += '\n' + p_strPad + 'srcFilter: ' + this.str_fConstruct(p_objItem.srcFilter, p_intLevel + 1, strNewPad);   
        strResult += '\n' + p_strPad + 'fromElement: ' + this.str_fConstruct(p_objItem.fromElement, p_intLevel + 1, strNewPad);   
        strResult += '\n' + p_strPad + 'toElement: ' + this.str_fConstruct(p_objItem.toElement, p_intLevel + 1, strNewPad);   
        strResult += '\n' + p_strPad + 'target: ' + this.str_fConstruct(p_objItem.target, p_intLevel + 1, strNewPad);   
        return strResult; 
    }
    
    clsConsole.prototype.str_fConstructDom = function(p_objItem, p_intLevel, p_strPad)
    {
        var strNewPad = p_strPad + '    ';
        var strResult = '';
        p_strPad = strNewPad;
        strResult += '\n' + p_strPad + 'id: ' + p_objItem.id;
        strResult += '\n' + p_strPad + 'className: ' + p_objItem.className;
        strResult += '\n' + p_strPad + 'nodeName: ' + p_objItem.nodeName;
        strResult += '\n' + p_strPad + 'nodeType: ' + p_objItem.nodeType;
        strResult += '\n' + p_strPad + 'nodeValue: ' + p_objItem.nodeValue;
        strResult += '\n' + p_strPad + 'tabIndex: ' + p_objItem.tabIndex;
        strResult += '\n' + p_strPad + 'tagName: ' + p_objItem.tagName;
        strResult += '\n' + p_strPad + 'title: ' + p_objItem.title;
        strResult += '\n' + p_strPad + 'readOnly: ' + p_objItem.readOnly;
        strResult += '\n' + p_strPad + 'disabled: ' + p_objItem.disabled;
        strResult += '\n' + p_strPad + 'type: ' + p_objItem.type;
        strResult += '\n' + p_strPad + 'clientWidth: ' + p_objItem.clientWidth;
        strResult += '\n' + p_strPad + 'clientHeight: ' + p_objItem.clientHeight;
        strResult += '\n' + p_strPad + 'offsetLeft: ' + p_objItem.offsetLeft;
        strResult += '\n' + p_strPad + 'offsetTop: ' + p_objItem.offsetTop;
        strResult += '\n' + p_strPad + 'offsetWidth: ' + p_objItem.offsetWidth;
        strResult += '\n' + p_strPad + 'offsetHeight: ' + p_objItem.offsetHeight;
        strResult += '\n' + p_strPad + 'scrollLeft: ' + p_objItem.scrollLeft;
        strResult += '\n' + p_strPad + 'scrollTop: ' + p_objItem.scrollTop;
        strResult += '\n' + p_strPad + 'scrollWidth: ' + p_objItem.scrollWidth;
        strResult += '\n' + p_strPad + 'scrollHeight: ' + p_objItem.scrollHeight;
        strResult += '\n' + p_strPad + 'style: ' + this.str_fConstruct(p_objItem.style, p_intLevel + 1, strNewPad);
        strResult += '\n' + p_strPad + 'dir: ' + p_objItem.dir;
        strResult += '\n' + p_strPad + 'lang: ' + p_objItem.lang;
        return strResult;         
    }
    
    clsConsole.prototype.fCreateConsole = function()
    {
        this.blnConstructed = true;
        //objParentElement = p_objParentElement;
        var objTable = document.createElement('TABLE');
        objTable.id = 'consoleTable';
        objTable.className = 'consoleTable';
        objTable.style.width = '100%';
        objTable.style.height = '100%';
        objTable.cellSpacing = 0;
        objTable.cellPadding = 0;
        
        var objRow1 = objTable.insertRow(0);
        var objCell = objRow1.insertCell(0);
        objCell.className = 'consoleHeader';
        objCell.innerHTML = '<span style="padding:2px;">Console</span>';
        
        objCell = objRow1.insertCell(1);
        objCell.className = 'consoleHeader';
        objCell.style.width = '80px';
        objCell.style.textAlign = 'right';
        
//        this.objCopyImg = document.createElement('IMG');
//		this.objCopyImg.id = 'consoleClipImg';
//		this.objCopyImg.src = cSYS.cIMAGE_PATH + '14_clipboard.gif';
//		this.objCopyImg.className = 'consoleButtons';
//		this.objCopyImg.title = 'Copy content to clipboard';
//		objCell.appendChild(this.objCopyImg);
//		addEvent(this.objCopyImg, 'click', this.fCopy, this);
		
        this.objMinimizeImg = document.createElement('IMG');
		this.objMinimizeImg.id = 'consoleMiniImg';
		this.objMinimizeImg.src = cSYS.cIMAGE_PATH + '14_minimize.gif';
		this.objMinimizeImg.className = 'consoleButtons';
		this.objMinimizeImg.title = 'Minimize';
		objCell.appendChild(this.objMinimizeImg);
		addEvent(this.objMinimizeImg, 'click', this.fMinimize, this);
		
		this.objMaximizeImg = document.createElement('IMG');
		this.objMaximizeImg.id = 'consoleMaxiImg';
		this.objMaximizeImg.src = cSYS.cIMAGE_PATH + '14_maximize.gif';
		this.objMaximizeImg.className = 'consoleButtons';
		this.objMaximizeImg.title = 'Maximize';
		objCell.appendChild(this.objMaximizeImg);
		addEvent(this.objMaximizeImg, 'click', this.fMaximize, this);
		
		this.objCloseImg = document.createElement('IMG');
		this.objCloseImg.id = 'consoleCloseImg';
		this.objCloseImg.src = cSYS.cIMAGE_PATH + '14_close2.gif';
		this.objCloseImg.className = 'consoleButtons';
		this.objCloseImg.title = 'Close console';
		objCell.appendChild(this.objCloseImg);
		addEvent(this.objCloseImg, 'click', this.fClose, this);
		
		this.objClosePermImg = document.createElement('IMG');
		this.objClosePermImg.id = 'consoleClosePermImg';
		this.objClosePermImg.src = cSYS.cIMAGE_PATH + '14_close_red.gif';
		this.objClosePermImg.className = 'consoleButtons';
		this.objClosePermImg.title = 'Close console permanently';
		objCell.appendChild(this.objClosePermImg);
		addEvent(this.objClosePermImg, 'click', this.fClosePerm, this);
		this.fSetButtonState();  
		       
        this.objContentRow = objTable.insertRow(1);
        this.objContentRow.style.height = '100%';
        objCell = this.objContentRow.insertCell(0);
        objCell.colSpan = 2;
        objCell.style.verticalAlign = 'top';
        objCell.style.backgroundColor = 'white';
        objCell.style.height = '100%';
        var objDiv = document.createElement('DIV');
        objDiv.style.height = '100%';
        objDiv.style.width = '100%';
        objDiv.style.overflow = 'auto';
        objDiv.style.position = 'relative';
        objDiv.style.backgroundColor = 'white';
        
        this.objDiv = document.createElement('DIV');
        this.objDiv.style.position = 'absolute';
        this.objDiv.style.padding = '2px';
        this.objDiv.id = 'console_div';
        objDiv.appendChild(this.objDiv);
        objCell.appendChild(objDiv);
        
        this.objFooterRow = objTable.insertRow(2);
        objCell = this.objFooterRow.insertCell(0);
        objCell.colSpan = 2;
        objCell.className = 'consoleFooter';
        objCell.style.textAlign = 'right';
        var objResizeImg = document.createElement('IMG');
		//objTitleImage.id = 'consoleCloseImg';
		objResizeImg.src = cSYS.cIMAGE_PATH + '14_resizer.gif';
		//objResizeImg.style.cursor = 'se-resize';
		objResizeImg.style.margin = '1px';
		objResizeImg.title = 'Close console';
		objCell.appendChild(objResizeImg);
        
        this.objMainElement.appendChild(objTable);
        this.g_fSetSize(200, 400);
        this.g_fSetConstraints({intMinWidth: 200, intMinHeight: 100, intMaxHeight: 500});
        this.g_fMakeDraggable(objRow1);
        this.g_fMakeResizable(objResizeImg, 'right', 'bottom');
    }
    
//    /**
//        Užkomentuota, nes ant BCing neturim g_fCopyToClipboard funkcijos, nes reiktų specialių teisių
//    */
//    clsConsole.prototype.fCopy = function()
//    {
//        if (!this.objDiv)
//            return;        
//        var arr_objChildren = this.objDiv.childNodes;
//        var strText = '';
//        for (var i = 0, intLength = arr_objChildren.length; i < intLength; i++)
//        {
//            var objItem = arr_objChildren[i];
//            if (objItem.nodeType == '1') // jei elementai
//            {
//                if (objItem.nodeName.toLowerCase() == 'br')
//                {
//                    strText += '\n';
//                }
//                else 
//                {
//                    strText += g_str_fInnerText(objItem);
//                }
//            }
//            else
//            {
//                strText += objItem.nodeValue;
//            }
//        }
//        strText = strText.replace(/(\r\n|\n)/g, '\r\n'); // čia dėl to, kad windowsai vieno \n nelaiko naujos eilutės ženklu
//        g_fCopyToClipboard(strText);
//    }
    
    clsConsole.prototype.fMinimize = function()
    {
        this.intOldHeight = this.objMainElement.clientHeight;
        this.intOldWidth = this.objMainElement.clientWidth;
        this.objMainElement.style.height = '20px';
        this.objMainElement.style.width = '200px';
        this.objFooterRow.style.display = 'none';
        this.objContentRow.style.display = 'none';
        this.blnMinimized = true;
        this.fSetButtonState();
    }
    
    clsConsole.prototype.fMaximize = function()
    {
        this.objMainElement.style.height = this.intOldHeight + 'px';
        this.objMainElement.style.width = this.intOldWidth + 'px';
        this.objFooterRow.style.display = '';
        this.objContentRow.style.display = '';
        this.blnMinimized = false;
        this.fSetButtonState();
    }
    
    clsConsole.prototype.fClose = function()
    {
        this.g_fHide();
        this.g_fClear();
    }
    
    clsConsole.prototype.fClosePerm = function()
    {
        this.blnCanOpen = false;
        this.g_fHide();
        this.g_fClear();
    }
    
    clsConsole.prototype.fSetButtonState = function()
    {
        if (this.blnMinimized)
        {
            this.objMaximizeImg.style.display = ''; 
            this.objMinimizeImg.style.display = 'none';
        }
        else
        {
            this.objMaximizeImg.style.display = 'none'; 
            this.objMinimizeImg.style.display = '';    
        }
    }
    
    clsConsole.prototype.fInsertText = function (p_objNode, p_strText)
    {
        // Kol tekstas netelpa į konsolę, tai iš jos po vieną vaiką meta laukan
        while (p_objNode.innerHTML.length > this.intMaxSimbolCount)
        {
            p_objNode.removeChild(p_objNode.firstChild);
        }
        p_objNode.innerHTML += p_strText + '<br/>';    
        
    }
    
    clsConsole.prototype.g_fClear = function()
    {
        if (this.objDiv)
        {
            this.objDiv.innerHTML = '';  
        }
    }
    
    clsConsole.prototype.g_fAlertLine = function(p_objItem)
    {
        var strAlert = this.str_fConstruct(p_objItem, 1, '');
        alert(strAlert);  
    }
    
var g_objConsole = new clsConsole();

addEvent(window, 'unload', consoleUninit);

function consoleUninit()
{
    g_objConsole.g_fUninit();
}

/**
    Funkcija rašymui į konsolę. Ji automatiškai prideda ir parodo konsolės langą, bei atspausdina į jį paduotą 
    eilutę.
    @param p_strInput {string} Tekstas, kurį reikia atspausdinti.
*/
function console(p_objInput, p_intLevel)
{
    if (!g_blnShowConsole) return;
    if (!document.body)
        return consoleA(p_strInput, p_intLevel);
    if (window.parent != window && parent.console != null)
    {
        parent.console(p_objInput, p_intLevel);
        return;    
    }
    g_objConsole.g_fSetLevel(p_intLevel);
    g_objConsole.g_fPrintLine(p_objInput);
}

/**
    console funkcijos sinonimas
    @author KM
    @version 1 2006-10-12
*/
function o(p_strInput, p_intLevel)
{
    console(p_strInput, p_intLevel)    
}

function consoleF(p_objInput, p_intLevel)
{
    if (!g_blnShowConsole) return;
    if (window.parent != window && parent.consoleF != null)
    {
        parent.consoleF(p_objInput, p_intLevel);
        return;    
    }
    g_objConsole.g_fSetLevel(p_intLevel);
    var blnSetting = g_objConsole.g_bln_fGetShowFunctions();
    g_objConsole.g_fSetShowFunctions(true);
    g_objConsole.g_fPrintLine(p_objInput);
    g_objConsole.g_fSetShowFunctions(blnSetting);
}

function consoleA(p_objInput, p_intLevel)
{
    if (!g_blnShowConsole) return;
    if (window.parent != window && parent.consoleA != null)
    {
        parent.consoleA(p_objInput, p_intLevel);
        return;    
    }
    g_objConsole.g_fSetLevel(p_intLevel);
    g_objConsole.g_fAlertLine(p_objInput);
}

function oa(p_objInput, p_intLevel)
{
    consoleA(p_objInput, p_intLevel);
}

function a(p_strInput, p_intLevel)
{
    consoleA(p_strInput, p_intLevel);
}


function consoleClear()
{
    if (!g_blnShowConsole) return;
    if (window.parent != window && parent.consoleClear != null)
    {
        parent.consoleClear();
        return;    
    }
    g_objConsole.g_fClear();    
}


function consoleSize(p_intLeft, p_intTop, p_intWidth, p_intHeight)
{
    if (!g_blnShowConsole) return;
    if (window.parent != window && parent.consoleSize != null)
    {
        parent.consoleSize(p_intLeft, p_intTop, p_intWidth, p_intHeight);
        return;    
    }
    g_objConsole.g_fSetSize(p_intWidth, p_intHeight);
    g_objConsole.g_fSetPosition(p_intLeft, p_intTop);     
}

function consoleClose()
{
    if (!g_blnShowConsole) return;
    if (window.parent != window && parent.consoleClose != null)
    {
        parent.consoleClose();
        return;    
    }
    g_objConsole.g_fClose(); 
}

function consoleClosePerm()
{
    if (!g_blnShowConsole) return;
    if (window.parent != window && parent.consoleClosePerm != null)
    {
        parent.consoleClosePerm();
        return;    
    }
    g_objConsole.g_fClosePerm();
}

// Konsolė \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

//<><><>////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////                                                 ///////////////
////////////////                  Drag handling                  ///////////////
////////////////                                                 ///////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

/**
    Globalus draginimo objektas. Registruoja draginimo platformą.
    @author KM
    @param p_strPlatformId - jei null, tai draginimo platforma - visas dokumentas.
*/
function clsDraggableManager(p_strPlatformId)
{
    this.strDragType = null;
    this.g_objDragedObject = null;
    this.g_objPreDragedObject = null;
    this.g_blnDragStarted = false;
    this.hsh_arr_objZones = {};
    
    if (cFF)
    {
        this.objEmptyCaptDiv = document.createElement('DIV');
        this.objEmptyCaptDiv.tabIndex = -1;        
        //this.objEmptyCaptDiv.style.position = 'absolute';
        
    }
    
    this.g_fRegisterPreDrag = function(p_hshEvent)
    {
        if (this.g_blnDragStarted)
            return; 
        this.g_objCurrentDropZone = null;
        this.g_objPreDragedObject = p_hshEvent['object'];
        this.g_blnDragStarted = true;  
        if (cFF)
        {
            // Tuščią divą dedam ne į tą elementą kuris yra užregistruotas, o į tą, už kurio draginama.
            var objSrcElement = getSrcElement(p_hshEvent['event']);
            objSrcElement.appendChild(this.objEmptyCaptDiv);
            //objSrcElement.insertBefore(this.objEmptyCaptDiv, objSrcElement.firstChild);
            this.objEmptyCaptDiv.focus();
        }
        if (cIE)
        {
           //console('setCapture nuimtas');
           document.body.setCapture();
        }
    }
    
    this.g_fRegisterDrag = function(p_hshEvent)
    {
        this.strDragType = p_hshEvent['strType'];
        this.g_objDragedObject = p_hshEvent['object'];
        this.g_objPreDragedObject = null;
        this.g_blnDragStarted = true;
    }
    
    this.g_fDrag = function(p_hshEvent)
    {
        if (this.g_objDragedObject)
        {
            p_hshEvent['draggedObject'] = this.g_objDragedObject;
            this.g_objDragedObject.g_fDrag(p_hshEvent); 
            this.fCheckDroppables(p_hshEvent);
            if (this.g_objCurrentDropZone != null)
            {
                this.g_objCurrentDropZone.g_fDrag(p_hshEvent);
            }
        }
        else if (this.g_objPreDragedObject)
        {
            this.g_objPreDragedObject.g_fPreDrag(p_hshEvent);
        }
    }
    
    this.g_fRestoreSelection = function()
    {
        if (cFF)
            document.body.style.MozUserSelect = '';
    }
    //------------------------------------------------------------
    
    
    this.g_fDragEnd = function(p_hshEvent)
    {
        this.g_fRestoreSelection();
        if (this.g_objDragedObject)
        {
            if (this.g_objCurrentDropZone)
            {
                p_hshEvent['dropPlace'] = this.g_objCurrentDropZone;
                this.g_objDragedObject.g_fDragEnd(p_hshEvent);   
                p_hshEvent['draggedObject'] = this.g_objDragedObject;
                delete p_hshEvent['dropPlace'];
                this.g_objCurrentDropZone.g_fAcceptDraggable(p_hshEvent);    
            }  
            else
            {
                this.g_objDragedObject.g_fDragFailed(p_hshEvent);
            }
            this.strDragType = null;
            this.g_objDragedObject = null;  
        }
        if (cIE && document && document.body && document.body.releaseCapture)
            document.body.releaseCapture(); 
        this.g_objPreDragedObject = null;
        this.g_blnDragStarted = false;
        this.g_objCurrentDropZone = null;
    }
    
    /**
        Priregistruoja vieną zoną
    */
    this.g_fAddDroppable = function(p_objDroppable, p_strType)
    {
        if (this.hsh_arr_objZones[p_strType] == null)
        {
            this.hsh_arr_objZones[p_strType] = [p_objDroppable];     
        }
        else
        {
            this.hsh_arr_objZones[p_strType].push(p_objDroppable);    
        }
    }
    
    this.fCheckDroppables = function(p_hshEvent)
    {
        var objPoint = g_obj_fGetMousePoint(p_hshEvent['event']);
        p_hshEvent['point'] = objPoint; 
        var arr_objZones = this.hsh_arr_objZones[this.strDragType];
        if (arr_objZones)
        {
            var arr_objOver = [];
            for (var i = 0, intLength = arr_objZones.length; i < intLength; i++)
            {
                var currHandle = arr_objZones[i].g_obj_fGetHandle();
                var objZoneRegion = g_obj_fGetRegion(currHandle);
                arr_objZones[i].g_objRegion = objZoneRegion;
                
                if (objZoneRegion.g_bln_fContains(objPoint))
                {
                    arr_objOver.push(arr_objZones[i]);            
                }  
            }
            if (arr_objOver.length == 0)
            {
                this.fSetNewCurrentDroppable(null, p_hshEvent);
            }
            else if (arr_objOver.length == 1)
            {
                this.fSetNewCurrentDroppable(arr_objOver[0], p_hshEvent);
            }
            else
            {
                var intMaxIndex = 0;
                for (var i = 1, intLength = arr_objOver.length; i < intLength; i++)
                {
                    if (arr_objOver[i].g_objRegion.g_int_fSize() < arr_objOver.g_objRegion.g_int_fSize())
                    {
                        intMaxIndex = i;
                    }
                }
                this.fSetNewCurrentDroppable(arr_objOver[intMaxIndex], p_hshEvent);
            }
        }
        else
        {
            this.fSetNewCurrentDroppable(null, p_hshEvent);
        }
    }
    
    this.fSetNewCurrentDroppable = function(p_objDroppable, p_hshEvent)
    {
        if (p_objDroppable != this.g_objCurrentDropZone)
        {
            if (this.g_objCurrentDropZone != null)
            {
                this.g_objCurrentDropZone.g_fMouseOut(p_hshEvent);
            }
            if (p_objDroppable != null)
            {
                p_objDroppable.g_fMouseOver(p_hshEvent);
            }
            this.g_objCurrentDropZone = p_objDroppable;
        }
    }
    
    this.g_fInit = function()
    {
        
        if(this.strPlatformId == null)
		{
			addEvent(document,'mousemove', this.g_fDrag, this);
			addEvent(document, 'mouseup', this.g_fDragEnd, this);
		}
		else
		{
			var objPlatform = document.getElementById(this.strPlatformId);
			if (objPlatform)
			{
			    addEvent(objPlatform,'mousemove', this.g_fDrag, this);
			    addEvent(objPlatform, 'mouseup', this.g_fDragEnd, this);
			}
			else
			{
			    addEvent(document,'mousemove', this.g_fDrag, this);   
			    addEvent(document, 'mouseup', this.g_fDragEnd, this); 
			}
		}
		//this.g_blnInitted = true;    
    }
    
    this.g_fUninit = function()
	{
		if(this.strPlatformId == null)
		{
			removeEvent(document,'mousemove', this.g_fDrag, this);
			removeEvent(document, 'mouseup', this.g_fDragEnd, this);
		}
		else
		{
			var objPlatform = document.getElementById(this.strPlatformId);
			if (objPlatform)
			{
			    removeEvent(objPlatform,'mousemove', this.g_fDrag, this);
			    removeEvent(objPlatform, 'mouseup', this.g_fDragEnd, this);
			}
			else
			{
                removeEvent(document,'mousemove', this.g_fDrag, this);   
			    removeEvent(document, 'mouseup', this.g_fDragEnd, this); 
			}
		}
		this.g_blnInitted = false;
	}
    
    this.strPlatformId = p_strPlatformId;
    this.g_fInit();
}

var g_objDrager = new clsDraggableManager(null);

/**
    objektas clsDraggable.
    Funkcijos:
        Pradedant draginti iškviečiamas įvykis, kurio metu galima iš originalios vietos išimti html elementą,
        arba sukurti kopiją.
        Draginant po pele turi būti vaizduojamas draginamas objektas arba jo kopija.
        Dropinant reikia numatyti į kurią vietą galima dropinti, beto dropinimo vieta turi priimti tik tam 
        tikro tipo drag elementus 
    Generuoja įvykius:
        cDragStart,
        cDrag,
        cDragEnd
    @param p_objHandle - Html elementas, už kurio galima draginti.
    @param p_strType - Draginamo objekto tipas (Čia kai reiks daryti drag&drop).
    @param p_objRelative - Html elementas, pagal kurį reikia skaičiuoti koordinates. Jei null, tai skaičiuojama pagal dokumentą.
    Generuojamiems įvykiams paduoda vieną parametrą, kuris yra hashas ir turi tokias komponentes:
        strType: Tipas
        object: clsDraggable objektas
        hshHandleOffset: Pradinio pelės paspaudimo offsetas handle viduje. Hashas, kurio vidus: 
            intXStartDiff: Handle pradžios ir pelės paspaudimo X koordinatės skirtumas; 
            intYStartDiff: Handle pradžios ir pelės paspaudimo Y koordinatės skirtumas; 
            intXEndDiff: Handle pabaigos ir pelės paspaudimo X koordinatės skirtumas; 
            intYEndDiff: Handle pabaigos ir pelės paspaudimo Y koordinatės skirtumas; 
        X: Reliatyvi pelės X koordinatė
        Y: Reliatyvi pelės Y koordinatė
        Kai įvykis yra DragEnd, tai turi ir tokią komponentę
        hshFirstCoords: 
            X: Pradinio paspaudimo reliatyvi X koordinatė
            Y: Pradinio paspaudimo reliatyvi Y koordinatė
    @author KM
    @version 1 2007.02.08
*/
function clsDraggable(p_objHandle, p_strType, p_objRelative)
{
    if (!p_objHandle)
        return;
    
    this.hshValues = {};
    this.iEvents = iEventInterface;
    this.iEvents([cEvents.cDragStart, cEvents.cDrag, cEvents.cDragEnd, cEvents.cDragFailed]);
    this.fInit(p_objHandle, p_strType, p_objRelative);
}
//------------------------------------------------------------

    clsDraggable.prototype.fInit = function(p_objHandle, p_strType, p_objRelative)
    {
        if(typeof(p_objHandle) == 'string')
        {
            p_objHandle = document.getElementById(p_objHandle);    
        }
        this.objDragHandle = p_objHandle;
        
        this.objRelativeElement = p_objRelative;
        
        this.g_strType = p_strType;
        if (this.g_strType == null)
        {
            this.g_strType = 'default';    
        }
        //this.objDragHandle.style.zIndex = '50';	
        addEvent(this.objDragHandle, 'mousedown', this.g_fPreDragStart.closure(this));
        if (cIE)
            addEvent(this.objDragHandle, 'dragstart', g_fStopEvent); 
        if (cFF)
        {
            addEvent(this.objDragHandle, 'draggesture', g_fStopEvent);   
            // Kažkas buvo čia uždėjęs KM 07.12.04
            //addEvent(this.objDragHandle, 'mousedown', this.g_fRestoreSelection.closure(this));  
        }
    }
    //------------------------------------------------------------

    clsDraggable.prototype.g_fPreDragStart = function(p_hshEvent)
    {     
        // Reikia, kad and Mozilos neselectintų teksto, kai draginam ir selektintų kai nedraginam
        if (!g_bln_fIsLeftClick(p_hshEvent['event']))
            return;
        if (cFF)
        {
            document.body.style.MozUserSelect = 'none';     
        }
        p_hshEvent['object'] = this;
        g_objDrager.g_fRegisterPreDrag(p_hshEvent);
        //g_fStopEvent(p_hshEvent['event']);
        
        this.objInitialGCoords = g_obj_fGetMousePoint(p_hshEvent['event']);
        //console(this.objInitialGCoords);
        this.objInitialLCoords = g_obj_fMakeRelative(this.objInitialGCoords, this.objRelativeElement);
        //console(this.objInitialLCoords);
        var objHandleRegion = g_obj_fGetRegion(this.objDragHandle);
        //console(this.objInitialLCoords);
        
        this.intXStartDiff = objHandleRegion.X - this.objInitialGCoords.X;
        this.intYStartDiff = objHandleRegion.Y - this.objInitialGCoords.Y;
        this.intXEndDiff = objHandleRegion.X + objHandleRegion.W - this.objInitialGCoords.X;
        this.intYEndDiff = objHandleRegion.Y + objHandleRegion.H - this.objInitialGCoords.Y;
        this.hshHandleOffset = {intXStartDiff: this.intXStartDiff, intYStartDiff: this.intYStartDiff, 
            intXEndDiff: this.intXEndDiff, intYEndDiff: this.intYEndDiff};
    }
    //------------------------------------------------------------
    
    clsDraggable.prototype.g_fPreDrag = function(p_hshEvent)
    {
        var objGCoords = g_obj_fGetMousePoint(p_hshEvent['event']);
        var dx = this.objInitialGCoords.X - objGCoords.X;
        var dy = this.objInitialGCoords.Y - objGCoords.Y;
        if (dx * dx + dy * dy > 2 * 2) // Pradedam dragą
        {
            this.g_fDragStart(p_hshEvent);    
        }
    }
    //------------------------------------------------------------

    
    clsDraggable.prototype.g_fDragStart = function(p_hshEvent)
    {    
        p_hshEvent['strType'] = this.g_strType;
        p_hshEvent['object'] = this;
        g_objDrager.g_fRegisterDrag(p_hshEvent);
        
        this.objLastGCoords = g_obj_fGetMousePoint(p_hshEvent['event']);
        this.objLastLCoords = g_obj_fMakeRelative(this.objLastGCoords, this.objRelativeElement);
        this.intXStartDiff += this.objInitialLCoords.X - this.objLastLCoords.X;
        this.intYStartDiff += this.objInitialLCoords.Y - this.objLastLCoords.Y;
        this.intXEndDiff += this.objInitialLCoords.X - this.objLastLCoords.X;
        this.intYEndDiff += this.objInitialLCoords.Y - this.objLastLCoords.Y;
//        this.hshHandleOffset = {intXStartDiff: this.intXStartDiff, intYStartDiff: this.intYStartDiff, 
//            intXEndDiff: this.intXEndDiff, intYEndDiff: this.intYEndDiff};
        this.objInitialGCoords = this.objLastGCoords;
        this.objInitialLCoords = this.objLastLCoords;
        p_hshEvent['hshHandleOffset'] = this.hshHandleOffset;
        p_hshEvent['X'] = this.objLastLCoords.X;
        p_hshEvent['Y'] = this.objLastLCoords.Y;
        p_hshEvent['global'] = this.objLastGCoords;
        p_hshEvent['firstGlobalCoords'] = this.objInitialGCoords;
        p_hshEvent['firstLocalCoords'] = this.objInitialLCoords;
        
		this.fFireEvent(cEvents.cDragStart, p_hshEvent); 
        this.blnFirstDrag = true;
        this.g_fDrag(p_hshEvent);   
    }
    //------------------------------------------------------------
    
    clsDraggable.prototype.g_fDrag = function(p_hshEvent)
    {
        p_hshEvent['object'] = this;
        
        this.objLastGCoords = g_obj_fGetMousePoint(p_hshEvent['event']);
        this.objLastLCoords = g_obj_fMakeRelative(this.objLastGCoords, this.objRelativeElement);
        p_hshEvent['hshHandleOffset'] = this.hshHandleOffset;
        p_hshEvent['X'] = this.objLastLCoords.X;
        p_hshEvent['Y'] = this.objLastLCoords.Y;
        p_hshEvent['global'] = this.objLastGCoords;
        p_hshEvent['firstGlobalCoords'] = this.objInitialGCoords;
        p_hshEvent['firstLocalCoords'] = this.objInitialLCoords;
        
        g_fStopEvent(p_hshEvent['event']);
		this.fFireEvent(cEvents.cDrag, p_hshEvent);
    }
    //------------------------------------------------------------

    
    clsDraggable.prototype.g_fDragEnd = function(p_hshEvent)
    {
        // Reikia, kad and Mozilos neselectintų teksto, kai draginam ir selektintų kai nedraginam
        //alert('g_fDragEnd');
        //this.g_fRestoreSelection();
            
        p_hshEvent['object'] = this;
        p_hshEvent['hshHandleOffset'] = this.hshHandleOffset;
        p_hshEvent['X'] = this.objLastLCoords.X;
        p_hshEvent['Y'] = this.objLastLCoords.Y;
        p_hshEvent['global'] = this.objLastGCoords;
        p_hshEvent['firstGlobalCoords'] = this.objInitialGCoords;
        p_hshEvent['firstLocalCoords'] = this.objInitialLCoords;

        this.fFireEvent(cEvents.cDragEnd, p_hshEvent);   
    } 
    //------------------------------------------------------------
    
    clsDraggable.prototype.g_arr_fGetCurrentCoordinates = function()
    {
        return this.arr_intLastCoords;
    }
    //------------------------------------------------------------
    
    clsDraggable.prototype.g_arr_fGetFirstCoordinates = function()
    {
        return this.arr_intFirstCoords;
    }
    //------------------------------------------------------------
    
    clsDraggable.prototype.g_fDragFailed = function(p_hshEvent)
    {
        // Reikia, kad and Mozilos neselectintų teksto, kai draginam ir selektintų kai nedraginam
        //this.g_fRestoreSelection();
            
        p_hshEvent['object'] = this;
        p_hshEvent['hshHandleOffset'] = this.hshHandleOffset;
        p_hshEvent['X'] = this.objLastLCoords.X;
        p_hshEvent['Y'] = this.objLastLCoords.Y;
        p_hshEvent['global'] = this.objLastGCoords;
        p_hshEvent['firstGlobalCoords'] = this.objInitialGCoords;
        p_hshEvent['firstLocalCoords'] = this.objInitialLCoords;
        
        this.fFireEvent(cEvents.cDragFailed, p_hshEvent);     
    }
    //------------------------------------------------------------
        
    clsDraggable.prototype.g_fUninit = function()
    {
        removeEvent(this.objDragHandle, 'mousedown', this.g_fPreDragStart.closure(this)); 
        if (cIE)
            removeEvent(this.objDragHandle, 'dragstart', g_fStopEvent); 
        if (cFF)
            removeEvent(this.objDragHandle, 'draggesture', g_fStopEvent);
        this.objDragHandle = null;
        this.objDragBlock = null;
    } 
    //------------------------------------------------------------

    clsDraggable.prototype.g_obj_fGetHandle = function()
    {
        return this.objDragHandle;
    }
    //------------------------------------------------------------
    
    clsDraggable.prototype.g_fSetBlock = function(p_objElement)
    {
        this.objBlock = p_objElement;
    }
    //------------------------------------------------------------
   
    clsDraggable.prototype.g_obj_fGetBlock = function()
    {
        return this.objBlock;
    }  
    //------------------------------------------------------------  

    clsDraggable.prototype.g_fSetValue = function(p_strKey, p_objValue)
    {
        this.hshValues[p_strKey] = p_objValue;
    }
    //------------------------------------------------------------
    
    clsDraggable.prototype.g_obj_fGetValue = function(p_strKey)
    {
        return this.hshValues[p_strKey];
    }
    //------------------------------------------------------------

// ------------------------------------------------------------------------------------------

// ------------------------------------------------------------------------------------------
/**
    clsDroppable klasė.
    Funkcijos:
        Dropinant reikia numatyti į kurią vietą galima dropinti, beto dropinimo vieta turi priimti tik tam 
        tikro tipo drag elementus.
        Draginant reikia nuspėti į kurią vietą dropinsim ir toje vietoje vaizduoti kokį žymeklį. 
    Generuoja įvykius:
        cDragOver,
        cDragOut,
        cDrop 
    @param p_objHandle - html objektas - zona į kurią bus metami draggable objektai. 
    @author KM
    @version 1 2007.02.08
*/
function clsDroppable(p_objHandle, p_arr_strTypes)
{
    if (!p_objHandle)
        return;
    
    this.hshValues = {};
    this.iEvents = iEventInterface;
    this.iEvents([cEvents.cDragOver, cEvents.cDrag, cEvents.cDragOut, cEvents.cDrop]);
    
    this.fInit(p_objHandle, p_arr_strTypes);	
}
//------------------------------------------------------------

    clsDroppable.prototype.fInit = function(p_objHandle, p_arr_strTypes)
    {
        if(typeof(p_objHandle) == 'string')
        {
            p_objHandle = document.getElementById(p_objHandle);    
        }
        this.objDropHandle = p_objHandle;
        this.arr_strTypes = p_arr_strTypes;
                
        if (this.arr_strTypes == null || this.arr_strTypes.length == 0)
        {
            g_objDrager.g_fAddDroppable(this, 'default');        
        }
        else
        {
            var intLength = this.arr_strTypes.length;
            for (var i = 0; i < intLength; i++)
            {
                g_objDrager.g_fAddDroppable(this, this.arr_strTypes[i]);    
            }
        }
    }
    //------------------------------------------------------------
    
    clsDroppable.prototype.g_fMouseOver = function(p_hshEvent)
    {
        p_hshEvent['object'] = this;
        this.fFireEvent(cEvents.cDragOver, p_hshEvent);    
    }
    //------------------------------------------------------------
    
    clsDroppable.prototype.g_fMouseOut = function(p_hshEvent)
    {
        p_hshEvent['object'] = this;
        this.fFireEvent(cEvents.cDragOut, p_hshEvent);
    }
    //------------------------------------------------------------
    
    clsDroppable.prototype.g_fDrag = function(p_hshEvent)
    {
        p_hshEvent['object'] = this;
        
        this.fFireEvent(cEvents.cDrag, p_hshEvent);
    }
    //------------------------------------------------------------
    
    clsDroppable.prototype.g_fAcceptDraggable = function(p_hshEvent)
    {
        p_hshEvent['object'] = this;
        this.fFireEvent(cEvents.cDrop, p_hshEvent);    
    }  
    //------------------------------------------------------------      
    
    clsDroppable.prototype.g_obj_fGetHandle = function()
    {
        return this.objDropHandle;
    }
    //------------------------------------------------------------
    
    clsDroppable.prototype.g_fSetValue = function(p_strKey, p_objValue)
    {
        this.hshValues[p_strKey] = p_objValue;
    }
    //------------------------------------------------------------
    
    clsDroppable.prototype.g_obj_fGetValue = function(p_strKey)
    {
        return this.hshValues[p_strKey];
    }
    //------------------------------------------------------------

// Drag handling \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

//<><><>////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////                                                 ///////////////
////////////////                 History manager                 ///////////////
////////////////                                                 ///////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

/**
 * @class HistoryManager
 * 
 * Reaguoja į url pasikeitimus ir atitinkamai reaguoja.
 * Išsaugo url pasikeitimus į būsenas, tarp kurių galima vaikščioti su back ir forward mygtukais.
 * Leidžia užregistruoti modulius, kurie išsaugotų savo būsenas url'e už # simbolio.
 * Singleton objektas, jo kopijuoti ar kaip kitaip kelis kartus sukūrinėti negalima.
 *  
 * @version		1.0rc2
 * 
 * @see			Events, Options
 * @link http://digitarald.de/playground/history.html
 * @license		MIT License
 * @author		Harald Kirschner <mail [at] digitarald.de>
 * @copyright	2007 Author
 */
var g_objHistoryManager = {};

// observeDelay: Duration for checking the state, default 100ms
g_objHistoryManager.g_intCheckingInterval = 100;
g_objHistoryManager.g_intSeparator = ';';
g_objHistoryManager.g_strIframeSrc = 'private/history.html';
g_objHistoryManager.blnStarted = false;
g_objHistoryManager.strState = null;
g_objHistoryManager.strBackState = "";

g_objHistoryManager.hshDataOptions = 
{
	skipDefaultMatch: true,
	defaults: [],
	regexpParams: ''
};

    /**
	 * Užregistruoja modulį.
	 * Modulis yra toks objektas, kuris gali nustatyti url bei gauti jo reikšmę bei atitinkamai reaguoti.
	 * @memberOf g_objHistoryManager
	 * @return	{Object} Object url ir istorijos modulio objektas su funkcijomis setValues, setValue, generate ir unregister
	 * 
	 * @param	{String} p_strId Modulio raktas
	 * @param	{Array} p_arrDefaultValues Pradinės reikšmės, kurios bus sujungos su einamomis reikšmėmis ir paduodamos į metodus onMatch ir onGenerate
	 * @param	{Function} p_fOnMatch funkcija, kuri bus kviečiama kai regexp išraiška matchina url'ą.
	 * @param	{Function} p_fOnGenerate turi grąžinti būsenas sudėtas į eilutę, reikšmių masyvas yra pirmas argumentas
	 * @param	{RegExp} p_objRegexp Reguliari išraiška, kuri matchina url ir gaudo modulio reikšmes
	 * @param	{Object} p_objContext Kontekstas, kuriame kviečiamos p_fOnMatch ir p_fOnGenerate funkcijos
	 */
    g_objHistoryManager.g_obj_fRegister = function(p_strId, p_arrDefaultValues, p_fOnMatch, p_fOnGenerate, p_objRegexp, p_objContext)
    {
        //console('g_objHistoryManager.g_obj_fRegister');
        if (!this.arr_objModules)
            this.g_fInit();    
        var hshData = g_hsh_fMergeHashes(this.hshDataOptions, {defaults: p_arrDefaultValues, onMatch: p_fOnMatch, onGenerate: p_fOnGenerate, regexp: p_objRegexp});
        hshData['context'] = p_objContext; // Jo negalima merginti, nukopijuotų šį objektą.
        hshData.regexp = hshData.regexp || p_strId + '-([\\w_-]*)';
        if (typeof hshData.regexp == 'string') 
            hshData.regexp = new RegExp(hshData.regexp, hshData.regexpParams);
        hshData.onGenerate = hshData.onGenerate || function(values) { return p_strId + '-' + values[0]; };
        hshData.values = g_obj_fClone(hshData.defaults);  
        hshData.id = p_strId;  
        this.hsh_objModules[p_strId] = hshData;
        if (this.strStartState && this.blnStarted) 
        {
            this.g_fCheckOneModule(this.strStartState, hshData);
            this.g_fUpdate();
        }
        return {
            setValues: function(p_arrValues) {
			    return this.g_fSetValues(p_strId, p_arrValues);
		    }.closure(this),
		    setValue: function(p_intIndex, p_strValue) {
			    return this.g_fSetValue(p_strId, p_intIndex, p_strValue);
		    }.closure(this),
		    generate: function(p_arr_strValues) {
			    return this.g_str_fGenerate(p_strId, p_arr_strValues);
		    }.closure(this),
		    unregister: function() {
			    return this.g_fUnregister(p_strId);
		    }.closure(this),
		    getValues: function() {
			    return this.g_arr_fGetValues(p_strId);
		    }.closure(this)
        }
    }
    
	/**
	 * unregister - Removes an module from the
	 * @memberOf g_objHistoryManager
	 * @param	{String} Module key
	 */
    g_objHistoryManager.g_fUnregister = function(p_strId) 
    {
		this.modules[p_strId] = null;
	}
	
	/**
	    Gauna prieš tai buvusią būseną.
	*/
	g_objHistoryManager.g_str_fGetBackState = function() 
    {
	    return this.strBackState;
    }
    
    /**
	    Gauna prieš tai buvusią būseną.
	*/
	g_objHistoryManager.g_str_fGetFullBackState = function() 
    {
	    var href = top.location.href;
	    var pos = href.indexOf('#') + 1;
	    var strBack = this.strBackState;
	    if (strBack.indexOf('#') != 0)
	        strBack = '#' + strBack;
	    href = href.substring(0, pos) + strBack;
	    console(href);
	    return href;
	    
	    return this.strBackState;
    }
    
	g_objHistoryManager.g_str_fGetStartState = function() 
    {
	    return this.strStartState;
    }
    
    g_objHistoryManager.g_str_fGetState = function() 
    {
	    return this.strState;
    }
	
    
    /**
        Init function
	    @memberOf g_objHistoryManager
	*/	
    g_objHistoryManager.g_fInit = function() 
    {
	    if (this.hsh_objModules) return this;
	    this.hsh_objModules = {};
    }
    	
    /**
	    @memberOf g_objHistoryManager
	    Start - Check hash and start observer
	    Call start after registering ALL modules. This start the observer,
	    and checks this state changes.
	*/
    g_objHistoryManager.g_fStart = function() 
    {
	    //console('g_objHistoryManager.g_fStart');
	    if (!this.blnStarted)
	    {
	        var objCaller = new clsIntervalCaller(this.g_fCheck, this, this.g_intCheckingInterval);
	        objCaller.g_fStartInterval();
	        this.blnStarted = true;
	    }
	    this.strStartState = this.str_fGetState();
	    this.g_fCheck();
	    this.g_fUpdate();
    }
    
    /**
        @memberOf g_objHistoryManager
        Checks current state and calls onMatch for affected modules.
    */
    g_objHistoryManager.g_fCheck = function()
    {
        var strNewState = this.str_fGetState();
        //console(strNewState + " :: " + this.strState);
        
//        p_strState = p_strState == null ? '' : p_strState; 
//	    p_strState = p_strState || '';
//	    var strLocHash = top.location.hash;
//	    console(strLocHash + " :& " + this.str_fGetState() + " : " + strNewState);
//	    if (strLocHash == strNewState || strLocHash == '#' + strNewState)
//	        return;
	    
        
        
        if (strNewState == this.strState)
            return;
        if (this.strState != null)
        {
            //console('-- Location');
            //console(top.location.href);
            this.strBackState = this.strState;//this.strCurrStateUrl;//top.location.href;
            //console('Back state:' + this.strBackState);
        }
        this.strCurrStateUrl = top.location.href;
        this.strState = strNewState;
//        console('g_fCheck pasikeitė');
//        console(strNewState);
    
        if (cIE && (this.strState !== null)) 
        {
//            console('Ivykdom IE SetState');
            this.fSetState(this.strState, true);
        }
        //console('g_fCheck');
        for (var strId in this.hsh_objModules)
        {
            var hshData = this.hsh_objModules[strId];
            //console(hshData.regexp);
            this.g_fCheckOneModule(this.strState, hshData);
        }  
    }
    
    g_objHistoryManager.g_fCheckOneModule = function(p_strState, p_hshModule)
    {
        //console('g_objHistoryManager.g_fCheckOneModule');
        var hshData = p_hshModule;
        var objMatch = p_strState.match(hshData.regexp)
        //console('g_fCheckOneModule');
        //console(objMatch);
        //console(p_hshModule.id);
        if (objMatch)
        {
            //console('Matchina');
            ////console(strId);
            //console(objMatch);
            objMatch.splice(0, 1);
            //console(objMatch);
            objMatch.complement(hshData.defaults);
            //console(objMatch);
            //console('---');
            if (!objMatch.isSimilar(hshData.defaults))
                hshData.values = objMatch;
            else
                hshData.values = g_obj_fClone(hshData.defaults);
            //console(hshData.values);
            //console('<><><>');
        }
        else
        {
            hshData.values = g_obj_fClone(hshData.defaults);
        }
        //console('--');
        //console('vistiek vykdo');
        //console(hshData.values);
        //console('--');
        hshData.onMatch.apply(hshData.context, [hshData.values, hshData.defaults]);
    }
    
    g_objHistoryManager.g_bln_fMatchOneModule = function(p_strState, p_hshModule)
    {
        //console('g_objHistoryManager.g_bln_fMatchOneModule');
        var objMatch = p_strState.match(p_hshModule.regexp);
        return !!objMatch;
    }
    
    /**
        @memberOf g_objHistoryManager
        @private
	    Gets Location.Hash property.
    */
    g_objHistoryManager.str_fGetHash = function()
    {
        var href = top.location.href;
	    var pos = href.indexOf('#') + 1;
	    return (pos) ? href.substr(pos) : '';
    }     
    
    /**
        @memberOf g_objHistoryManager
	    Generates state from all registered modules.
    */
    g_objHistoryManager.g_str_fGenerateState = function() 
    {
	    //console('g_objHistoryManager.g_str_fGenerateState');
	    var arrState = [];
	    //console('Generate state >');
	    for (var strId in this.hsh_objModules)
        {
            //console('Modulis ' + strId);
            var hshData = this.hsh_objModules[strId];
            if (hshData.values.isSimilar(hshData.defaults))
            {
                if (!this.g_bln_fMatchOneModule(this.strState, hshData) && hshData.skipDefaultMatch)
                    continue;
            }
            
            //console('Defaultai:');
            //console(hshData.defaults);
            //console('Reikšmės:');
            //console(hshData.values);            
            var strStateToken = hshData.onGenerate.apply(hshData.context, [hshData.values]);
            //console('Ateina tokenas: ' + strStateToken);
            if (strStateToken != '')
                arrState.push(strStateToken);
        }
        //console('<');
        //console(arrState);
        //console('>');
        return arrState.join(this.g_intSeparator);
    }
    
    /**
	    @memberOf g_objHistoryManager
	    g_str_fGenerate - Generates a hash from the given
	  
	    @param	{String} Module key
	    @param	{String[]} Values
	*/
	g_objHistoryManager.g_str_fGenerate = function(p_strId, p_arr_strValues) 
	{
		//console('g_objHistoryManager.g_str_fGenerate');
		var hshData = this.hsh_objModules[p_strId];
		var current = g_obj_fClone(hshData.values);
		//console(hshData.values);
		hshData.values = p_arr_strValues;
		//console(hshData.values);
		var state = this.g_str_fGenerateState();
		hshData.values = current;
		//console(hshData.values);
		return '#' + state;
	}
    
    /**
        @memberOf g_objHistoryManager
	    Updates current state.
    */
    g_objHistoryManager.g_fUpdate = function() 
    {
		//console('g_objHistoryManager.g_fUpdate');
		if (!this.blnStarted) 
		    return;
		var strState = this.g_str_fGenerateState();		
		//consoleA('g_objHistoryManager.g_fUpdate');
		//consoleA(strState);
		//consoleA('/end');
//		if ((!this.strState && !strState) || (this.strState == strState)) 
//		    return;
		this.fSetState(strState);
	}
	
	/**
	    @memberOf g_objHistoryManager
	    @private
	    Gets state from hash or from iframe.
	*/
	g_objHistoryManager.str_fGetState = function()
    {
        var state = this.str_fGetHash();
        if (this.iframe) {
			var doc = this.iframe.contentWindow.document;
			if (doc && doc.body.id == 'state') {
				var istate = doc.body.innerText;
				if (this.strState == state) 
				    return istate;
				this.blnIsStateOld = true;
			} else return this.strIState;
		}
		return state;
    }    

    /**
        Sets state.
        
        @memberOf g_objHistoryManager
        @private
	    @param	{String} New state string
        @param  {bool} Flag that determines whether iframe should be updated for IE
    */
	g_objHistoryManager.fSetState = function(p_strState, p_blnFix)
	{
	    this.strBackState = this.strState;
        //console('Back state:' + this.strBackState);
	    //console('g_objHistoryManager.fSetState');
	    p_strState = p_strState == null ? '' : p_strState; 
	    p_strState = p_strState || '';
	    var strLocHash = top.location.hash;
	    //consoleA(strLocHash + " :& " + this.str_fGetState() + " : " + p_strState);
	    //consoleA(strLocHash + " :& " + p_strState);
	    this.strState = p_strState;
	    if (!(strLocHash == p_strState || strLocHash == '#' + p_strState))
	    {
	        //consoleA('Ne praėjom');
	        if (p_strState == "")
	            p_strState = "#";
	        top.location.hash = p_strState;
	        //consoleA('hash pakeistas');
	    // top.location.hash pasetinimas ant IE iškviečia tick soundą, todėl reikia vykdyti jų kuo mažiau
	    }
	    //consoleA('fSetState baigėsi');
	    if (cIE && (!p_blnFix || this.blnIsStateOld))
	    {
	        if (!this.iframe) {
				this.iframe = document.createElement('iframe');
				this.iframe.src = cSYS.cABS_VIRTUAL_PATH + this.g_strIframeSrc;
				this.iframe.style.visibility = 'hidden';
				this.iframe.style.width = '0px';
				this.iframe.style.height = '0px';
				document.body.appendChild(this.iframe);
				this.strIState = this.strState;
			}
			try {
				var doc = this.iframe.contentWindow.document;
				doc.open();
				doc.write('<html><body id="state">' + p_strState + '</body></html>');
				doc.close();
				this.blnIsStateOld = false;
			} catch(e) {};
		}
		this.strState = p_strState;
	}

	/**
	    setValues - Set all values new, updates new state
        @memberOf g_objHistoryManager
	    @param	{String} Module key
	    @param	{Object} Complete values
	 */
	g_objHistoryManager.g_fSetValues = function(p_strId, p_arr_strValues)
	{
	    //console('g_objHistoryManager.g_fSetValues');
	    var hshData = this.hsh_objModules[p_strId];
//	    console('g_objHistoryManager.g_fSetValues');
//	    console(p_arr_strValues);
//	    console(hshData.values);
	    if (!hshData || hshData.values.isSimilar(p_arr_strValues)) 
	        return;
//	    console('Update vyksta');
        //console('g_objHistoryManager.g_fSetValues');
        //console(hshData.values);
		hshData.values = p_arr_strValues;
		console(hshData.values);
		this.g_fUpdate();
	}
	
    /**
        setValue - Set one value, updates new state
        @memberOf g_objHistoryManager
	    @param	{String} Module key
        @param	{Number} Value index
        @param	{Object} Value
     */
	g_objHistoryManager.g_fSetValue = function(p_strId, p_intIndex, p_strValue)
	{
	    //console('g_objHistoryManager.g_fSetValue');
	    //o('g_fSetValue '+p_strId+ ' '+ p_intIndex+' '+ p_strValue);
	    var hshData = this.hsh_objModules[p_strId];
	    if (!hshData || hshData.values[p_intIndex] == p_strValue) 
	        return;
		//console(hshData.values);
		hshData.values[p_intIndex] = p_strValue;
		//console(hshData.values);
		this.g_fUpdate();
	}
	
	/**
	    Gets module values
	*/
	g_objHistoryManager.g_arr_fGetValues = function(p_strId)
	{
	    var hshData = this.hsh_objModules[p_strId];
	    if (!hshData) 
	        return [];
		return hshData.values;
	}

g_objHistoryManager.g_fInit();

// History manager \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

//<><><>////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////                                                 ///////////////
////////////////                 Key manager                     ///////////////
////////////////                                                 ///////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

    
/**
    Skirta universaliam veiksmų iškvietimui klavišais.
    @author Rimantas Sipkus
    @version 1.0 2007.01.09
    @constructor
*/    
function clsKeyManager(p_strId, p_objPlatform)
{
    this.g_strId = p_strId;
    var objThis = this;
    if(p_objPlatform == null) p_objPlatform = document;
    var objPlatform = p_objPlatform;
    var arr_hshKeyMap = new Array();
    var arr_hshFKeyMap = new Array();
    var blnEnabled = true;
    //-----------------------------------------------
    this.g_fSetEnabled = function(p_blnEnabled)
    {
        blnEnabled = p_blnEnabled;
    }
    //-----------------------------------------------
    /**
        @p_fHandler - funkcija kuris bus vykdoma pagavus registruotą klavišą
        @p_intKey - raidė ARBA
                    simbolio kodas ARBA
                    Klavišo hashas (iš jau sudarytų), pvz g_objDefaultKeysMap.cNEW, tuomet nereikia paduoti nieko daugiau
        @p_blnCtrl - ar reikalingas nuspaustas Ctrl
        @p_blnShift - ar reikalingas nuspaustas Shift
        @p_blnAlt - ar reikalingas nuspaustas Alt
        @p_strTag - operacijos tagas (reikalingas tam kad butų galima identifikuoti operacijas CASE'e)
        @p_blnStopDefault - ar iškvietus handlerį stabdyti įvykį
    */
    this.g_fRegister = function(p_fHandler, p_intKey, p_blnCtrl, p_blnShift, p_blnAlt, p_strTag, p_blnStopDefault)
    {
        //var blnIsFKey = false;
        var hshKey = new Object();
        if(typeof(p_intKey) == 'object')
        {
            hshKey = p_intKey;
            if(typeof(hshKey['key']) == 'string')
            {
                hshKey['key'] = (hshKey['key']).charCodeAt(0);
            }
            //blnIsFKey = bln_fIsFKey(hshKey['key']);
            hshKey['handler'] = p_fHandler;
        }
        else
        {
            if(typeof(p_intKey) == 'string')
                hshKey['key'] = p_intKey.charCodeAt(0);
            if(typeof(p_intKey) == 'number')
            {
                hshKey['key'] = p_intKey;
            }
            //blnIsFKey = bln_fIsFKey(hshKey['key']);
            hshKey['ctrl'] = p_blnCtrl;
            hshKey['shift'] = p_blnShift;
            hshKey['alt'] = p_blnAlt;
            hshKey['handler'] = p_fHandler;
            hshKey['tag'] = p_strTag;
            hshKey['stopDefault'] = p_blnStopDefault;
        }
        //if(blnIsFKey || cIE || cFF)
            arr_hshFKeyMap.push(hshKey);
        //else
            //arr_hshKeyMap.push(hshKey);
    }
    //-----------------------------------------------
    function bln_fIsFKey(p_intCode)
    {
        for(intKey in g_objFKeys)
        {
            if(g_objFKeys[intKey] == p_intCode)
                return(true);
        }
        return(false);
    }
    //-----------------------------------------------
    var strUniqueId = 'GKM_' + Math.random() + '_' + new Date();
    function fInit()
    {
        g_objEventManager.g_fAddEvent(strUniqueId, 'keydown', fKeyDown);
        //g_objEventManager.g_fAddEvent(strUniqueId, 'keypress', fKeyPressed);
    }
    //-----------------------------------------------
    addEvent(window, 'unload', fUninit);
    function fUninit()
    {
        g_objEventManager.g_fRemoveEvent(strUniqueId, 'keydown');
        //g_objEventManager.g_fRemoveEvent(strUniqueId, 'keypress');
    }
    //-----------------------------------------------
    function fKeyDown(e, p_hshEvent)
    {
        //&& p_hshEvent['arr_intNavigation'] != null && p_hshEvent['arr_intNavigation'][0] != -1
        if(blnEnabled )
        {
            var intKey = g_int_fGetKeyCode(e);
            for(var i = 0;i < arr_hshFKeyMap.length;i++)
            {
                if(arr_hshFKeyMap[i]['key'] == intKey && arr_hshFKeyMap[i]['ctrl'] == e.ctrlKey && arr_hshFKeyMap[i]['shift'] == e.shiftKey && arr_hshFKeyMap[i]['alt'] == e.altKey)
                {
                    var hshEvent = new Object();
                    hshEvent['key'] = arr_hshFKeyMap[i]['key'];
                    hshEvent['ctrl'] = arr_hshFKeyMap[i]['ctrl'];
                    hshEvent['shift'] = arr_hshFKeyMap[i]['shift'];
                    hshEvent['tag'] = arr_hshFKeyMap[i]['tag'];
                    hshEvent['stopDefault'] = arr_hshFKeyMap[i]['stopDefault'];
                    hshEvent['event'] = e;
                    hshEvent['object'] = objThis;
                    if(hshEvent['stopDefault'])
                        g_fStopEvent(e);
                    // KMarc 2007-05-09
                    g_obj_fAsyncCallImediate(arr_hshFKeyMap[i]['handler'], null, 0, hshEvent);
                }
            }
        }
    }
    //-----------------------------------------------
    /*function fKeyPressed(e)
    {
        if(blnEnabled)
        {
            var intKey = g_int_fGetKeyCode(e);
            for(var i = 0;i < arr_hshKeyMap.length;i++)
            {
                if(arr_hshKeyMap[i]['key'] == intKey && arr_hshKeyMap[i]['ctrl'] == e.ctrlKey && arr_hshKeyMap[i]['shift'] == e.shiftKey && arr_hshKeyMap[i]['alt'] == e.altKey)
                {
                    var hshEvent = new Object();
                    hshEvent['key'] = arr_hshKeyMap[i]['key'];
                    hshEvent['ctrl'] = arr_hshKeyMap[i]['ctrl'];
                    hshEvent['shift'] = arr_hshKeyMap[i]['shift'];
                    hshEvent['tag'] = arr_hshKeyMap[i]['tag'];
                    hshEvent['stopDefault'] = arr_hshKeyMap[i]['stopDefault'];
                    hshEvent['event'] = e;
                    hshEvent['object'] = objThis;
                    arr_hshKeyMap[i]['handler'](hshEvent);
                    if(hshEvent['stopDefault'])
                        g_fStopEvent(hshEvent['event']);
                }
            }
        }
    }*/
    //-----------------------------------------------
    fInit();
    //-----------------------------------------------
}
var g_objKeyManager = new clsKeyManager('globalKeyManager');

/**
    Duomenų struktūra su funkcinių klavišų kodais.
    @author Rimantas Sipkus
    @version 1.0 2007.01.09
    @constructor
*/
function clsFKeys()
{
    this.cDEL = 46;
    this.cF1 = 112;
    this.cF2 = 113;
    this.cF3 = 114;
    this.cF4 = 115;
    this.cF5 = 116;
    this.cF6 = 117;
    this.cF7 = 118;
    this.cF8 = 119;
    this.cF9 = 120;
    this.cF10 = 121;
    this.cF11 = 122;
    this.cF12 = 123;
    this.cTAB = 9;
    this.cENTER = 13;
    this.cESC = 27;
    this.cPGUP = 33;
    this.cPGDOWN = 34;
    this.cEND = 35;
    this.cHOME = 36;
    this.cWINDOWS = 91;
    this.cCAPSLOCK = 20;
    this.cSPACE = 32;
}
var g_objFKeys = new clsFKeys();

/**
    Duomenų struktūra su standartinių veiksmų tagais ir juos sužadinančių klavišų informacija.
    @author Rimantas Sipkus
    @version 1.0 2007.01.09
    @constructor
*/
function clsKeysMap()
{
    this.cNEW = {ctrl:true, shift:false, alt:false, key:78, tag:'001', stopDefault:true};
    this.cDELETE = {ctrl:false, shift:false, alt:false, key:g_objFKeys.cDEL, tag:'002', stopDefault:true};
    this.cEDIT = {ctrl:true, shift:false, alt:false, key:69, tag:'003', stopDefault:true};
    this.cPRINT = {ctrl:true, shift:false, alt:false, key:80, tag:'004', stopDefault:true};
    this.cSEARCH = {ctrl:true, shift:false, alt:false, key:70, tag:'005', stopDefault:true};
    this.cSAVE = {ctrl:true, shift:false, alt:false, key:83, tag:'006', stopDefault:true};
    this.cHELP = {ctrl:false, shift:false, alt:false, key:g_objFKeys.cF1, tag:'007', stopDefault:true};
}
var g_objDefaultKeysMap = new clsKeysMap();

// Key manager \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

//<><><>////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////                                                 ///////////////
////////////////                 OOP funkcijos                   ///////////////
////////////////                                                 ///////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

/**
    Kopijuoja paduotą objektą išskiriant naują atmintį
    @author Kęstutis Malinauskas
    @param p_objInput Objektas, kurį reikia kopijuoti
    @returns Nukopijuotą objektą
    @type object
*/
function g_obj_fClone(p_objInput)
{
	if(typeof(p_objInput) != 'object') 
	{
	    if (p_objInput && p_objInput.constructor == RegExp)
	    {
	        return new RegExp(p_objInput);  
	    }
	    return p_objInput;
	}
	if(p_objInput == null) return p_objInput;
	var strFTypeOf = ftypeof(p_objInput);
	if (strFTypeOf == 'domelement')
	{
	    return p_objInput.cloneNode(true);
	}
    
    var objReturn;
    var fConstructor = p_objInput.constructor;
    if( fConstructor != null )
	{
		switch( fConstructor )
		{																	
			case Array:
			    objReturn = new Array();
				break;
			case Date:
			    return new Date(+p_objInput);
			case Object:
				objReturn = new Object();
				break;
			default:
				if (typeof(p_objInput.g_obj_fClone) == 'function')
				{
				    return p_objInput.g_obj_fClone();
				}
				else
				{
				    var sConstructor = fConstructor.toString();
				    var aMatch = sConstructor.match( /\s*function (.*)\(/ );
				    if( aMatch != null )
				    {
					    objReturn = new fConstructor();
				    }
				    else
				    {
				        objReturn = new Object();  
				    }
				}
			
		}
	}
//	if (p_objInput.length != null)
//	    objReturn = new Array();
//	else
//	    objReturn = new Object();

	for(var i in p_objInput)
		objReturn[i] = g_obj_fClone(p_objInput[i]);
		
	

	return objReturn;
}
//--------------------------------------------------------------------------------------

/**
    Įgyvendina Sub klasės paveldėjimą iš Base klasės. Šią funkciją reikia vykdyti globaliai, žemiau 
    klasių aprašų. 
    Vaikinės klasės konstruktoriuje taip pat reikia iškviesti tokią funkciją:
    clsSubClass.baseConstructor.call(this, pBaseClassConstructorArguments);
    @author KM
    @version 1 2006.10.02
*/
function g_fExtend(p_clsSubClass, p_clsBaseClass) 
{
   function inheritance() {}
   inheritance.prototype = p_clsBaseClass.prototype;

   p_clsSubClass.prototype = new inheritance();
   p_clsSubClass.prototype.constructor = p_clsSubClass;
   p_clsSubClass.baseConstructor = p_clsBaseClass;
   p_clsSubClass.superClass = p_clsBaseClass.prototype;
}



/**
    Funkcija, gaunanti detalesnį objekto tipą nei typeof().
    http://www.webreference.com/dhtml/column68/
    JS object	    ftypeof() return value
 
    Boolean 	    boolean
    Function        function
    Number 	        number
    String 	        string
    [ no object ]   undefined
     
    Arguments	    arguments
    Array 	        array
    Date 	        date
    Error 	        error
    Math 	        math
    Null 	        null
    Object 	        jsobject
    RegExp 	        regexp
    [ custom ] 	    CustomConstructorFunctionName
    
*/
function ftypeof( vExpression )
{	
	var sTypeOf = typeof vExpression;
	if( sTypeOf == "function" )
	{
		return 'function';
//		var sFunction = vExpression.toString();
//		if( ( /^\/.*\/$/ ).test( sFunction ) )
//		{
//			return "regexp";
//		}
//		else if( ( /^\[object.*\]$/i ).test( sFunction ) )
//		{
//			sTypeOf = "object"
//        }
	}
	if( sTypeOf != "object" )
	{
		return sTypeOf;
	}
	
	switch( vExpression )
	{
		case null:
			return "null";
		case window:
			return "window";
		case window.event:	
			return "event";
	}
	
	if( window.event && ( event.type == vExpression.type ) )
	{
		return "event";
	}
	
	if(vExpression.eventPhase != null && vExpression.type != null)
	{
	    return 'event';
	}
	
	var fConstructor = vExpression.constructor;
    if( fConstructor != null )
	{
		switch( fConstructor )
		{																	
			case Array:
				sTypeOf = "array";
				break;
			case Date:
				return "date";
			case RegExp:
				return "regexp";
			case Object:
				sTypeOf = "jsobject";
				break;
			case ReferenceError:
				return "error";
			default:
				var sConstructor = fConstructor.toString();
				var aMatch = sConstructor.match( /\s*function (.*)\(/ );
				if( aMatch != null )
				{
					return 'jsobject';//+aMatch[ 1 ];
				}
			
		}
	}

	var nNodeType = vExpression.nodeType;
	if( nNodeType != null )
	{	
		switch( nNodeType )
		{
			case 1:
				if( vExpression.item == null )
				{
					return "domelement";
				}
				break;
			case 3:
				return "textnode";
		}
	}
	
	if( vExpression.toString != null )
	{
		var sExpression = vExpression.toString();
		var aMatch = sExpression.match( /^\[object (.*)\]$/i );
		if( aMatch != null )	
		{
			var sMatch = aMatch[ 1 ];
			switch( sMatch.toLowerCase() )
			{
				case "event":
					return "event";
				case "math":
					return "math";
				case "error":	
					return "error";
				case "mimetypearray":
					return "mimetypecollection";
				case "pluginarray":
					return "plugincollection";
				case "windowcollection":
					return "window";
				case "nodelist":
				case "htmlcollection":
				case "elementarray":
					return "domcollection";
			}
		}
	}
	
	if( vExpression.moveToBookmark && vExpression.moveToElementText )
	{
		return "textrange";
	}
	else if( vExpression.callee != null )
	{
		return "arguments";
	}
	else if( vExpression.item != null )	
	{
		return "domcollection";
	}
	
	return sTypeOf;
}

// OOP funkcijos \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

//<><><>////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////                                                 ///////////////
////////////////               Vertimų funkcijos                 ///////////////
////////////////                                                 ///////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

/**
    Skirtas dinaminiam vertimui.
*/
function g_fDynaTranslate(p_objElement)
{
    var objData = new Object();
    objData['project'] = 'CMC';
    objData['file'] = cSYS.cLANG_PATH;
    objData['tag'] = p_objElement.innerHTML;
    var hshRet = openDialog(cSYS.cLANG_TOOL_PATH + 'forms/frmTagEdit.aspx', 400, 500, objData, 'no');
    if(hshRet != null)
    {
        if(p_objElement != null && p_objElement.innerHTML)
        {
            p_objElement.innerHTML = hshRet[cSYS.cLANG];
        }
    }
}

// JScript File

/**
    @requires g_objConfiguration
*/
function clsLightMenu(p_hshArg, p_hshEvents, p_arr_intPositions, p_blnRelativeToMouse, p_intMaxNodes)
{
    var objThis = this;
	var hshTempArg = p_hshArg;
	var hshArg = p_hshArg;
	// p_hshArg['strId'];
	// p_hshArg['strParentId']
	// hshArg['NodeWidth'], 
	// hshArg['NodeHeight']
	var hshEvents = p_hshEvents;
	// hshEvents['MenuClick']
    // hshEvents['BuildMenu']
    // hshEvents['HideMenu']
    // hshEvents['ShowMenu']
    var arr_intPositions = p_arr_intPositions;
    var blnRelativeToMouse = p_blnRelativeToMouse;
    var arr_intMousePosition;
    var objCallerElement;
    var blnIsIn = false;
    var blnMoves = false;
    var blnWasClosed = false;
    var arr_objNodes = null;
    var hsh_intTypeCounts = null;
    var strLastSelectedId = null;
    var strPrefix = 'lightMenu_';
    var intMaxNodes = p_intMaxNodes;
    
    /**
	    Gaunamas elementas pagal galinę Id dalį. Pradinė Id dalis yra paimama iš dialogo Id.
	    @param p_strRelativeId Reliatyvus objekto Id.
	    @returns Rastą HTML objektą su nurodytu reliatyviu id.
	    @type HTML object
	*/
	this.g_obj_fGetLocalElement = function(p_strRelativeId)
    {
        return document.getElementById(this.g_str_fCreateId(p_strRelativeId));
    }
    
    /**
	    Funkcija skirta kurti elementų Id. Ji apjungia dialogo id ir elemento reliatyvų id. 
        Dialogai turi turėti globalų kintamąjį - id.
	    @param p_strElementId Reliatyvus objekto Id.
	    @returns Pilną objekto id.
	    @type HTML object
	*/
    this.g_str_fCreateId = function(p_strElementId)
    {
        return strFilterId + '_' + p_strElementId;
    }
    
    this.g_fInit = function()
    {
        arr_objNodes = new Array();
        hsh_intTypeCounts = new Object();
        fConstructMenu(hshTempArg);  
    }
    
    this.g_fUninit = function()
    {
        var objMainDiv = document.getElementById(hshArg['strId']); 
        if (objMainDiv)
        {
            removeEvent(objMainDiv, 'mouseover', fOver);
            removeEvent(objMainDiv, 'mouseout', fOut);
            removeEvent(objMainDiv, 'mousemove', fMove);
            g_objEventManager.g_fRemoveEvent(hshArg['strId'], 'click');  
            var objParent = document.getElementById(p_hshArg['strParentId']);
	        removeEvent(objParent,'contextmenu',g_fStopEvent);   
	        if(cIE == true)
			    removeEvent(objMainDiv,'selectstart',g_fStopEvent);
			removeEvent(objMainDiv,'contextmenu',g_fStopEvent); 
        }           
    }
    
    function fOver(e)
    {
        blnIsIn = true;    
    }
    
    function fOut(e)
    {
        blnIsIn = false;  
        if (strLastSelectedId)
        {
            var objRow = document.getElementById(strPrefix + strLastSelectedId);
            if (objRow) fSetStyle(objRow, false);
        }  
        strLastSelectedId = null;
    }
    
    function fMove(e)
    {
        blnMoves = true;    
        var objElement = getSrcElement(e);
        var strRowId = objElement.getAttribute('strRowId');
        if (!strRowId) return;
        if (strLastSelectedId == strRowId) return;
        if (strLastSelectedId)
        {
            var objRow = document.getElementById(strPrefix + strLastSelectedId);
            if (objRow) fSetStyle(objRow, false);
        }
        strLastSelectedId = strRowId;        
        var objRow = document.getElementById(strPrefix + strRowId);
        if (objRow) fSetStyle(objRow, true);
    }
    
    this.g_fOpen = function(p_objCallerEvent)
    {
        fOpenMenu(p_objCallerEvent);
    }
    
    this.g_arr_fGetState = function(p_blnNeedToMove)
    {
        var blnCanBeClosed = false;
        if (p_blnNeedToMove)
        {
            blnCanBeClosed = !blnIsIn || !blnMoves;
            blnMoves = false;
            return blnResult;
        }
        else
        {
            blnMoves = false;
            blnCanBeClosed = !blnIsIn;
        }
        return [blnWasClosed,  blnCanBeClosed, blnIsIn];
    }
    
    this.g_fClose = function()
    {
        objThis.g_fHide();    
    }
    
    
    
    //////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////        Pagalbinės funkcijos         //////////////////////////
    //////////////////////////////////////////////////////////////////////////////////////////
    
    function fConstructMenu(p_hshArg)
	{
		hshArg = new Object();
		if (typeof(g_objConfiguration) != 'undefined')
		{
		    hshArg = g_obj_fClone(g_objConfiguration.g_hshContextMenuCmc);
		}
	    for (var key in p_hshArg)
	    {
	        hshArg[key] = p_hshArg[key];    
	    }
        
        var objParent = document.getElementById(p_hshArg['strParentId']);
	    addEvent(objParent,'contextmenu',g_fStopEvent);   
        objParent.setAttribute('strTagName', 'strTd_HMenu');
	    objParent.setAttribute('strTopMenuId', p_hshArg['strParentId']);
	    g_fCreateContent(hshArg);
    }
      
	
	function fMenuClick(p_hshEvent)
	{
	    blnIsIn = false;
	    blnWasClosed = true;
	    var strNode = p_hshEvent['strNode'];
	    var objEvent = p_hshEvent['event'];
	    if (typeof(hshEvents['MenuClick']) == 'function')
	    {
	        hshEvents['MenuClick'](strNode);    
	    }   
	}
	
	function fOpenMenu(p_hshEvent)
	{
	    blnWasClosed = false;
	    arr_intMousePosition = p_hshEvent['event']['mousePosition'];
	    objCallerElement = p_hshEvent['element'];
	    objThis.g_fHide();
	    objThis.g_fDeleteAll();
	    if (typeof(hshEvents['BuildMenu']) == 'function')
	    {
	        hshEvents['BuildMenu'](p_hshEvent, objThis);        
	    }
	    if (arr_objNodes == null || arr_objNodes.length == 0)
	    {
	        objThis.g_fHide();
	    }
	    else
	    {
	        fShowMenu(arr_intPositions, hshArg['NodeWidth'], hshArg['NodeHeight'], objCallerElement, arr_intMousePosition);
	    }
	}
   
    function fShowMenu(p_arr_intPosition, p_intNodeWidth, p_intNodeHeight, p_objParentObj, p_arr_intMousePosition)
    {
        var hshTemp = new Object();
        var arr;
        var textNodeCount = objThis.g_int_fGetCountOfType('text');
        var breakerNodeCount = objThis.g_int_fGetCountOfType('breaker');
        var intMenuHeight = textNodeCount * hshArg['NodeHeight'] + breakerNodeCount * 5;
        if (blnRelativeToMouse)
        {
            hshTemp = g_hsh_int_fGetCoordsByPosition(arr_intMousePosition[0], arr_intMousePosition[1], 
                0, 0, p_intNodeWidth, intMenuHeight, p_arr_intPosition);
            arr = [hshTemp['intX'], hshTemp['intY']];
        }
        else
        {
            var objParentObj = p_objParentObj; 
            var arrArg = objPosition(objParentObj);  
            hshTemp = g_hsh_int_fGetCoordsByPosition(arrArg[2], arrArg[3],arrArg[0],arrArg[1], 
                p_intNodeWidth, intMenuHeight, p_arr_intPosition);
            arr = g_arr_int_fGetCoords(p_objParentObj, hshTemp['intX'],hshTemp['intY']);    
        }
        objThis.g_fShow(arr[0], arr[1]); 
    }
	
    function fHideEventHandler() 
    {
        if (typeof(hshEvents['HideMenu']) == 'function')
        {
            hshEvents['HideMenu']();    
        }
    }
    function fShowEventHandler() 
    {
        if (typeof(hshEvents['ShowMenu']) == 'function')
        {
            hshEvents['ShowMenu']();    
        }
    }
    
    //////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////   Specifinės meniu funkcijos        //////////////////////////
    //////////////////////////////////////////////////////////////////////////////////////////
    
    function g_fCreateContent(hshArg)
    {
        var objParentDiv = document.getElementById(hshArg['strParentId']);
        if (objParentDiv)
        {
            var objMainDiv = document.getElementById(hshArg['strId']); 
            if (!objMainDiv)
            {
                objMainDiv = document.createElement('DIV');
                objMainDiv.style.position = 'absolute';
			    objMainDiv.id = hshArg['strId'];
			    objMainDiv.style.zIndex = hshArg['zindex'];
			    objMainDiv.style.display = 'none';
			    objMainDiv.style.visibility = 'hidden';
			    objMainDiv.style.cursor = 'default';
			    objMainDiv.style.border = hshArg['strMenuBorderStyle'];
			    if (hshArg['intNodeWidth'] != null)
			        objMainDiv.style.width = hshArg['intNodeWidth'];   
			    
			    objParentDiv.appendChild(objMainDiv);
			    
			    g_objEventManager.g_fAddEvent(hshArg['strId'], 'click', fClick); 
			    addEvent(objMainDiv, 'mouseover', fOver);
                addEvent(objMainDiv, 'mouseout', fOut);
                addEvent(objMainDiv, 'mousemove', fMove);
			    
			    if(cIE == true)
			        addEvent(objMainDiv,'selectstart',g_fStopEvent);
			    //console('Kuriamas meniu');
			    if(cFF == true)
			        objMainDiv.style.MozUserSelect = 'none';
			    addEvent(objMainDiv,'contextmenu',g_fStopEvent); 
			    
			    var objTable = document.createElement('table');
			    objTable.style.borderCollapse = 'collapse';
			    objTable.cellSpacing = '0';
			    objTable.cellPadding = '0';
			    objTable.id = hshArg['strId'] + '_table';
			    objMainDiv.appendChild(objTable);  
            }   
        }
    }
    
    this.g_fShow = function(p_intX, p_intY)
    {
        var objMainDiv = document.getElementById(hshArg['strId']);
	    if (objMainDiv)
	    {
	        objMainDiv.style.display = '';
			objMainDiv.style.visibility = 'visible';
			objMainDiv.style.position = 'absolute';
			objMainDiv.style.left = p_intX;
			objMainDiv.style.top = p_intY;
			if (intMaxNodes != null && intMaxNodes > 0 && arr_objNodes.length > intMaxNodes)
		    {
		        objMainDiv.style.height = intMaxNodes * hshArg['intNodeHeight'];
		        objMainDiv.style.overflow = 'auto';
		    } 
		    else
		    {
		        objMainDiv.style.height = '';       
		    }
			fShowEventHandler();
        }    
    }
    
    this.g_fHide = function()
    {
        var objMainDiv = document.getElementById(hshArg['strId']);
	    if (objMainDiv)
	    {
	        objMainDiv.style.display = 'none';
			objMainDiv.style.visibility = 'hidden';
			fHideEventHandler();
        }
    }
    
    this.g_fInsert = function(p_strParent, p_strItem, p_strText, p_strType)
    {
        var objMainTable = document.getElementById(hshArg['strId'] + '_table');
	    if (objMainTable)
	    {
	        var objTr = objMainTable.insertRow(objMainTable.rows.length);
	        objTr.setAttribute('strRowId', p_strItem);
	        objTr.setAttribute('strMenuId', hshArg['strId']);
	        objTr.id  = strPrefix + p_strItem;
	        objTr.style.height = hshArg['intNodeHeight'];
		    objTr.style.width = hshArg['intNodeWidth'];
	        
		    var objTd = objTr.insertCell(0);
		    objTd.setAttribute('strTagType', 'Item');
		    objTd.setAttribute('strMenuId', hshArg['strId']);
		    objTd.setAttribute('strRowId', p_strItem);
		    objTd.style.width = '20px';
		    
		    objTd = objTr.insertCell(1);		    		    
		    objTd.setAttribute('strTagType', 'Item');
		    objTd.setAttribute('strMenuId', hshArg['strId']);
		    objTd.setAttribute('strRowId', p_strItem);
		    objTd.style.paddingLeft = '5px';
		    objTd.style.paddingRight = '5px';
		    
		    objTd.innerHTML = p_strText;
		    
		    fSetStyle(objTr, false);
		    
		    var objNewItem = new Object();
		    objNewItem['strParent'] = p_strParent;
		    objNewItem['strItem'] = p_strItem;
		    objNewItem['strText'] = p_strText;
		    objNewItem['strType'] = p_strType;
		    if (typeof(hsh_intTypeCounts[p_strType]) == 'undefined')
		    {
		        hsh_intTypeCounts[p_strType] = 0;    
		    }
		    hsh_intTypeCounts[p_strType]++;
		    arr_objNodes.push(objNewItem);
        }   
    }
    
    function fSetStyle(p_objRow, p_blnSelected)
    {
        var objFirstCell = p_objRow.cells[0];
        var objSecondCell = p_objRow.cells[1];
        if (p_blnSelected)
        {
            objFirstCell.style.backgroundColor = hshArg['strSelectLeftColor'];
            objSecondCell.style.backgroundColor = hshArg['strSelectRightColor'];
        }
        else
        {
            objFirstCell.style.backgroundColor = hshArg['strLeftColor'];
            objSecondCell.style.backgroundColor = hshArg['strRightColor'];    
        }
    }
    
    this.g_fDeleteAll = function()
    {
        var objMainTable = document.getElementById(hshArg['strId'] + '_table');
	    if (objMainTable)
	    {
	        for (var i = objMainTable.rows.length - 1; i >= 0; i--)
	        {
	            objMainTable.deleteRow(i);
	        }
	        arr_objNodes = new Array();
		    hsh_intTypeCounts = new Object();
        }     
    }
    
    this.g_int_fGetCountOfType = function(p_strType)
    {
        if (typeof(hsh_intTypeCounts[p_strType]) == 'undefined')
	    {
	        return 0;    
	    }
	    return hsh_intTypeCounts[p_strType];    
    }
    
    function fClick(e, p_hshArg) 
	{   
	    if(p_hshArg['blnEventOnCurrDoc'] == true)
	    {
	        var objElement = getSrcElement(e);
            var strRowId = objElement.getAttribute('strRowId');
            var strMenuId = objElement.getAttribute('strMenuId');
            if (!strRowId || strMenuId != hshArg['strId']) 
            {
                objThis.g_fHide();    
            }
            else
            {
                var hshEvent = new Object();
                hshEvent['strNode'] = strRowId;
                hshEvent['event'] = e;
                fMenuClick(hshEvent);     
            }
	    }
	    else
	    {
	        objThis.g_fHide();     
	    }  
	}
}


// JScript File
var objTimeoutHelper = new Object();

/**
    p_strId, 
    p_arr_strElementsToHandle, 
    p_intTimeout, 
    p_fOpenFunction, 
    p_fCanClose, 
    p_fClose
*/
function clsNoClickEventShooter(p_strId, 
                                p_arr_strElementsToHandle, 
                                p_intTimeoutToShow,
                                p_intTransitionTimeout,
                                p_intTimeoutToHide,
                                p_blnNeedToMove,
                                p_fOpen, 
                                p_fCanClose, 
                                p_fClose)
{
    var cTimesToClose = 4;
    
    var strId = 'Shooter_' + p_strId;
    var arr_strElementsToHandle = p_arr_strElementsToHandle; 
    var intTimeoutToShow = p_intTimeoutToShow;
    var intTransitionTimeout = p_intTransitionTimeout;
    var intTimeoutToHide = p_intTimeoutToHide / cTimesToClose;
    var blnNeedToMove = p_blnNeedToMove;
    var fOpenHandler = p_fOpen; 
    var fCanCloseHandler = p_fCanClose; 
    var fCloseHandler = p_fClose;
    
    var objCurrentElementToShow = null;
    var objCurrentlyShownElement = null;
    var objCurrentEvent = null;
    var intSeed = 0;
    var blnIsOpened = false;
    var blnWasClosed = false;
    var arr_intMousePosition;
    
    var intLeftToClose;
    var blnInited = false;
    var blnGo = false;
    var blnBlocked = false;
    var blnIsOnMenu = false;
    
    var objThis = this;
    
    this.g_fStart = function()
    {
        blnGo = true; 
        if (!blnInited)	
	    {
	        fInit();    
	        blnInited = true;
	    }
    }
    
    this.g_fStop = function()
    {
        blnGo = false; 
    }
    
    function fInit()
    {
        objTimeoutHelper.g_fTimeoutFunction = fOpenOnDelay;
        addEvent(document, 'mouseover', fOver);
	    addEvent(document, 'mouseout', fOut);  
	    addEvent(document, 'mousedown', fMouseDown);   
	    addEvent(document, 'mousemove', fMouseMove); 
	    addEvent(window, 'unload', fUninit);
	}
	
	this.g_fUninit = function()
	{
	    fUninit();    
	}
	
	function fUninit()
	{
	    removeEvent(document, 'mouseover', fOver);
	    removeEvent(document, 'mouseout', fOut);   
	    removeEvent(document, 'mousedown', fMouseDown); 
	    removeEvent(document, 'mousemove', fMouseMove); 
	    removeEvent(window, 'unload', fUninit);    
	}     
	
	function fOver(e)
	{
	    if (!blnGo) return;
	    var objHTMLElement = getSrcElement(e);
        if (objHTMLElement != objCurrentElementToShow)
        {
            objCurrentElementToShow = objHTMLElement;      
        }
        if (objCurrentElementToShow == objCurrentlyShownElement) return;
        var intTimeout = blnIsOpened ? intTransitionTimeout : intTimeoutToShow;
        var intNextSeed = int_fGetNextSeed();
        var strDescriptor = objHTMLElement.id ? objHTMLElement.id : objHTMLElement;
        objHTMLElement.setAttribute(strId, intNextSeed);
        setTimeout('objTimeoutHelper.g_fTimeoutFunction(\'' + intNextSeed + '\')', intTimeout);   
	}    
	
	function fOut(e)
	{
	    if (!blnGo) return;
	    var objHTMLElement = getSrcElement(e);
	    objHTMLElement.removeAttribute(strId);   
	    var strDescriptor = objHTMLElement.id ? objHTMLElement.id : objHTMLElement;
	             
	}
	
	function fMouseDown(e)
	{
	    if (!blnGo) return;
	    if (!blnIsOpened && !blnIsOnMenu)
	    {
	        var objHTMLElement = getSrcElement(e);
	        objCurrentElementToShow = objHTMLElement; 
	        fShow(objCurrentElementToShow, true); 
	    } 
	}
	
	function fMouseMove(e)
	{
	    arr_intMousePosition = getMouse(e);
	}
	
	function fOpenOnDelay(p_intSeed)
	{
	    var strGotSeed = objCurrentElementToShow.getAttribute(strId);  
        if (!strGotSeed) return;
        var arr_blnState = arr_fCallGetState(true);
        if ((strGotSeed == p_intSeed) && arr_blnState[0] && !arr_blnState[1])
        {
            fShow(objCurrentElementToShow);    
        } 
	}
	
	function fCloseOnDelay()
	{
	    var arr_blnState = arr_fCallGetState();
	    if (arr_blnState[1])
	    {
	        fClose();              
	    }
	    else
	    if (arr_blnState[0])
	    {
	        intLeftToClose--; 
	        if (intLeftToClose <= 0)
	        {
	            fClose();       
	        }
	        else
	        {
	            setTimeout(fCloseOnDelay, p_intTimeoutToHide);     
	        }       
	    }
	    else
	    {
	        intLeftToClose = cTimesToClose;  
	        setTimeout(fCloseOnDelay, p_intTimeoutToHide);   
	    }
	}
	
	function fShow(p_objCurrentElementToShow, p_blnIgnoreRestrictions)
	{
	    if(!p_blnIgnoreRestrictions)
	    {
	        if (blnBlocked) return;
	        if (objCurrentlyShownElement == p_objCurrentElementToShow) return;
	    }
	    blnIsOpened = true;
	    objCurrentlyShownElement = p_objCurrentElementToShow;
	    var hshEvent = new Object();
	    hshEvent['event'] = new Object;
	    hshEvent['event']['mousePosition'] = arr_intMousePosition;
	    hshEvent['element'] = objCurrentlyShownElement;
	    if (typeof(fOpenHandler) == 'function')
        {
            fOpenHandler(hshEvent);
        }
        setTimeout(fCloseOnDelay, p_intTimeoutToHide);  
        intLeftToClose = cTimesToClose;
	}
	
	function fClose()
	{
	    blnIsOpened = false;
        if (typeof(fCloseHandler) == 'function')
        {
            fCloseHandler();   
        }   
        if (objCurrentlyShownElement != objCurrentElementToShow)
        {
            objCurrentlyShownElement = null;
            fShow(objCurrentElementToShow);    
        }
	}
	
	function arr_fCallGetState(p_blnIgnoreBlocked)
	{
	    if (typeof(fCanCloseHandler) != 'function')
	    {
	        blnBlocked = true;
	        return true;
	    } 
	    var arr_blnState = fCanCloseHandler(blnNeedToMove);
	    if (!p_blnIgnoreBlocked && arr_blnState[0] && blnBlocked == false)
	    {
	        blnBlocked = true;
	        setTimeout(fUnblock, intTimeoutToShow);   
	    }
	    blnIsOnMenu = arr_blnState[2];
	    return [arr_blnState[1], blnBlocked];
	}
	
	function fUnblock()
	{
	    blnBlocked = false;    
	}
	
	
	function int_fGetNextSeed()
	{
	    intSeed++;
	    if (intSeed > 1000000)
            intSeed = 0;
        return intSeed;   
	}  
}

var g_objTranslator = new clsTranslator();

function clsTranslator()
{
    var strId = 'Translator1';
    var objEventShooter;
    var objMenu;
    var intMaxMenuNodes = 50;
    var objCurrentEvent = null;
    var blnShowFull = false;
        
    this.g_fInit = function()
    {
        var objDiv = document.createElement('DIV');
        objDiv.id = strId;
        document.body.appendChild(objDiv);
        
        var hshArg = new Object();
	    hshArg['strId'] = strId + '_Menu';
	    hshArg['strParentId'] = strId;
	    hshArg['intNodeWidth'] = null;//230;
	    hshArg['intNodeHeight'] = 20;
	    hshArg['zindex'] = 1000;
	    hshArg['strMenuBorderStyle'] = '1px outset menu';//'1px solid #f00ff0';
	    hshArg['strRightColor'] = 'white';
        hshArg['strLeftColor'] = 'gainsboro';
        hshArg['strSelectLeftColor'] = 'silver';
        hshArg['strSelectRightColor'] = 'silver';
        hshArg['strNodeMenuBorderStyle'] = '1px outset menu';
        hshArg['strBreakerPicture'] = 'breaker.gif';
        hshArg['strDisabledFontColor'] = 'gray';
	    var hshEvents = new Object();
	    hshEvents['MenuClick'] = fMenuClick;
	    hshEvents['BuildMenu'] = fBuildMenu;
	    hshEvents['HideMenu'] = fHideMenu;
	    hshEvents['ShowMenu'] = fShowMenu;
	    var arr_intPositions = [9, 8, 6, 7, 3, 4, 2, 1, 5];
	    objMenu = new clsLightMenu(hshArg, hshEvents, arr_intPositions, true, 5);
	    objMenu.g_fInit();
        objEventShooter = new clsNoClickEventShooter('EventShooter1', null, 500, 200, 1000, false, 
	        objMenu.g_fOpen, objMenu.g_arr_fGetState, objMenu.g_fClose);
	    objEventShooter.g_fStart();
	    
        addEvent(window, 'unload', fUninit);
	}
	
	function fUninit()
	{
	    if (objEventShooter) objEventShooter.g_fUninit();
	    if (objMenu) objMenu.g_fUninit();
	    objCurrentEvent = null;
	    removeEvent(window, 'unload', fUninit);    
	}

    function fMenuClick(p_strNode)
    {
        g_fDynaTranslate(p_strNode);
    }
    
    /**
        Vertimo dialogo iškvietimo funkcija
    */
    function g_fDynaTranslate(p_strTag)
    {
        var objData = new Object();
        objData['project'] = 'CMCMain';
        objData['file'] = cSYS.cLANG_PATH;
        objData['tag'] = p_strTag;
        // Kviečiamas vertimo dialogas
        var hshRet = openDialog(cSYS.cLANG_TOOL_PATH + 'forms/frmTagEdit.aspx', 400, 500, objData, 'no');
        if(hshRet != null)
        {  
//            if(p_objElement != null && p_objElement.innerHTML)
//            {
//                p_objElement.innerHTML = hshRet[cSYS.cLANG];
//            }
        }
    }
    
    function fBuildMenu(p_objEvent, p_objMenu)
    {
        objCurrentEvent = p_objEvent;
        var hshResult = hshGetUntranslatedWords(p_objEvent['element']);
        for (var i = 0; i < hshResult['list'].length && (i < intMaxMenuNodes || blnShowFull); i++)
        {
            p_objMenu.g_fInsert('root', hshResult['list'][i], [hshResult['list'][i]], 'text');  
        }
//        if (!hshResult['fullList'])
//        {
//            p_objMenu.g_fInsert('root', '[expand]', ['...'], 'text');      
//        }     
        blnShowFull = false;       
    }
    
    function hshGetUntranslatedWords(p_objElement)
    {
        var hshResult = new Object();
        hshResult['fullList'] = true;
        hshResult['list'] = new Array();
        var hshStringHolder = new Object();
        var intGotWords = int_fGetUntranslatedWordsFromNode(hshStringHolder, p_objElement, 0);
        hshResult['fullList'] = blnShowFull ? true : intGotWords <= intMaxMenuNodes;
        for (var key in hshStringHolder)
        {
            hshResult['list'].push(key);    
        }
        return hshResult;
    }
    
    function int_fGetUntranslatedWordsFromNode(p_hshStringHolder, p_objNode, p_intGotWords)
    {
        var intGotWords = p_intGotWords;
        if (!p_objNode) return intGotWords;
        var i;
        intGotWords = int_fGetUntranslatedWordsFromString(p_hshStringHolder, p_objNode.innerHTML, intGotWords);  
        return intGotWords; 
//        if (p_objNode.attributes)
//        {
//            for (i = 0; i < p_objNode.attributes.length; i++)
//            {
//                intGotWords = int_fGetUntranslatedWordsFromString(p_hshStringHolder, p_objNode.attributes[i].value, intGotWords);  
//                if (!blnShowFull && intGotWords > intMaxMenuNodes) return intGotWords;
//            }
//        }
//        
//        if (p_objNode.nodeType == 3)
//        {
//            intGotWords = int_fGetUntranslatedWordsFromString(p_hshStringHolder, p_objNode.nodeValue, intGotWords);  
//            if (!blnShowFull && intGotWords > intMaxMenuNodes) return intGotWords;  
//        }
//        else if (p_objNode.childNodes)
//        {
//            for (i = 0; i < p_objNode.childNodes.length; i++)
//            {
//                intGotWords = int_fGetUntranslatedWordsFromNode(p_hshStringHolder, p_objNode.childNodes[i], intGotWords);  
//                if (!blnShowFull && intGotWords > intMaxMenuNodes) return intGotWords;  
//            }   
//        }
           
    }
    
    function int_fGetUntranslatedWordsFromString(p_hshStringHolder, p_strTestedString, p_intGotWords)
    {
        if (p_strTestedString == null) return p_intGotWords;
        var intGotWords = p_intGotWords;
        var arr = p_strTestedString.match(/\[([^\[\]]+)\]/g);
        //var arr = /\[([^\[\]]+)\]/g.exec(p_strTestedString);
        if (!arr) return intGotWords; 
        var substr = '';
        for (var i = 0; i < arr.length; i++)
        {
            substr = arr[i].substring(1, arr[i].length - 1);
            if (!p_hshStringHolder[substr]) intGotWords++;
            p_hshStringHolder[substr] = intGotWords;    
            if (!blnShowFull && intGotWords > intMaxMenuNodes) return intGotWords;  
        }
        return intGotWords; 
    }
    
    function fHideMenu()
    {
    }
    
    function fShowMenu()
    {
    }
}
//---------------------------------------------------------------

/**
    Sukuria mygtukus feedo peržiūrėjimui ir feedo įdėjimui į desktopą.
    @param p_objParent Tėvas, kur sudėti mygtukus
    @param p_strFeedURL Feedo adresas
    @param [p_strTitle] Feedo pavadinimas
*/
function g_fCreateFeedLink(p_objParent, p_strFeedURL, p_strTitle)
{
    p_objParent = g_obj_fElement(p_objParent);
    if (!p_objParent)
        return;
        
    var objAdder =  document.createElement('IMG');
    objAdder.src = cSYS.cIMAGE_PATH + 'bcfeed.gif';
    objAdder.border = 0;
    objAdder.style.verticalAlign = 'text-top';
    objAdder.style.cursor = 'pointer';
    objAdder.setAttribute('bclink', p_strFeedURL);
    objAdder.style.marginRight = '2px';
    if (p_strTitle)
        objAdder.setAttribute('bctitle', p_strTitle);
    
    
//    var objLink = document.createElement('A');
//    objLink.href = p_strFeedURL;
//    objLink.target = "blank";
//    
//    var objImage = document.createElement('IMG');
//    objImage.src = cSYS.cIMAGE_PATH + '14_feed_icon.png';
//    objImage.border = 0;
//    objImage.style.verticalAlign = 'middle';
//    objLink.appendChild(objImage);
//    objLink.style.marginRight = '2px';
    
    p_objParent.insertBefore(objAdder, p_objParent.firstChild);
//    p_objParent.insertBefore(objLink, p_objParent.firstChild);
    addEvent(objAdder, 'click', g_fAddFeedToDesktop);
}
//---------------------------------------------------------------

function g_fAddFeedToDesktop(p_objEvent)
{
    var objElement = getSrcElement(p_objEvent);
    var strTitle = objLang.g_str_fGetString('really_want_to_add_feed');
    var strMessage = objLang.g_str_fGetString('information');
    clsAlert.g_fPromptYesNo(strTitle, strMessage, null, fAddFeed, objElement);
}

function fAddFeed(p_strArg, objElement)
{
    if(p_strArg == 'yes')
    {
        var strLink = objElement.getAttribute('bclink');
        //o('feedo linkas');
        //console(strLink);
        if (!strLink)
            return;
        var strTitle = objElement.getAttribute('bctitle');  
        var strModuleName = 'clsFeedViewer' + Math.round(Math.random() * 10000); 
        var hshSettings = {modules: {}};
        hshSettings['modules'][strModuleName] = 
        {
            container: 'main', 
            type: 'clsFeedViewer', 
            contargs: {col: '0', row: '-1'}, 
            settings: {items: '10', source: strLink, title: strTitle}
        };
        //console('aaa');
        var strValue = g_str_fGetXmlFromObject(hshSettings, 'root', 10);
        var objResult = g_obj_fExecuteQuery('cmdSettingSet', {ITEM: 'root', VALUE: strValue, PAGE: 'default'}, function(){});
        //VU 2008-02-12 idejau langiuka, kuris pranesa apie feedo ikelima i desktopa
        //clsAlert.g_fInformation(objLang.g_str_fGetString('added_succesfully'), objLang.g_str_fGetString('added_succesfully'), null, function(){});
    }
}
//---------------------------------------------------------------

/**
    Suformuoja nuorodą į vartotojo profilį. Į nuorodą įeina vartotojo vardas ir pavardė. 
    Jei vartotojas yra ištrintas, tai grąžina tik tekstą.
    @param p_strId Vartotojo id
    @param p_strFName Vartotojo vardas
    @param p_strLName Vartotojo pavardė
    @param p_intStatus Vartotojo status
    @param p_strClassName Nuorodos klasės pavadinimas
    @returns HTML element
*/
function g_obj_fGetUserLink(p_strId, p_strFName, p_strLName, p_intStatus, p_strClassName)
{
    if (p_intStatus == 2 || p_intStatus == 3)
    {
        return document.createTextNode(p_strFName + ' ' + p_strLName);
    }
    else
    {
        var objReturn = document.createElement('A');
        objReturn.href = 'profile.aspx?uid=' +p_strId;
        objReturn.className = p_strClassName;
        var objContent = document.createTextNode(p_strFName + ' ' + p_strLName);
        objReturn.appendChild(objContent);
        return objReturn;
    }
}

/**
    Suformuoja nuorodą į vartotojo profilį, tačiau grąžina ne DOM objektą, o paruoštą HTML stringą, skirtą dėjimui į innerHTML. 
    Į nuorodą įeina vartotojo vardas ir pavardė. Jei vartotojas yra ištrintas, tai grąžina tik tekstą.
    @param p_strId Vartotojo id
    @param p_strFName Vartotojo vardas
    @param p_strLName Vartotojo pavardė
    @param p_intStatus Vartotojo status
    @param p_strClassName Nuorodos klasės pavadinimas
    @returns HTML element
*/
function g_str_fGetUserLinkSource(p_strId, p_strFName, p_strLName, p_intStatus, p_strClassName)
{
    if (p_intStatus == 2 || p_intStatus == 3)
    {
        return g_str_fEscapeXmlEntities(p_strFName + ' ' + p_strLName);
    }
    else
    {
        var strSource = '<a href="profile.aspx?uid=' + p_strId + '" class="' + p_strClassName + '">' + g_str_fEscapeXmlEntities(p_strFName + ' ' + p_strLName) + '</a>';
        return strSource;
    }
}

/**
    Suformuoja nuorodą į vartotojo profilį. Į nuorodą įdeda tai, kas yra paduodama p_objContent kintamuoju. 
    Jei vartotojas yra ištrintas, tai grąžina tik tai ką paduodam p_objContent kintamuoju.
    @param p_strId Vartotojo id
    @param p_objContent Elementas, kurį reikia dėti į linką
    @param p_intStatus Vartotojo status
    @param p_strClassName Nuorodos klasės pavadinimas
    @returns HTML element
*/
function g_obj_fGetUserLinkCustomContent(p_strId, p_objContent, p_intStatus, p_strClassName)
{
    if (p_intStatus == 2 || p_intStatus == 3)
    {
        return p_objContent;
    }
    else
    {
        var objReturn = document.createElement('A');
        objReturn.href = 'profile.aspx?uid=' +p_strId;
        objReturn.className = p_strClassName;
        objReturn.appendChild(p_objContent);
        return objReturn;
    }
}

/**
    Suformuoja nuorodą į vartotojo profilį. Į nuorodą įdeda tai, kas yra paduodama p_objContent kintamuoju. 
    Jei vartotojas yra ištrintas, tai grąžina tik tai ką paduodam p_objContent kintamuoju.
    @param p_strId Vartotojo id
    @param p_objContent Elementas, kurį reikia dėti į linką
    @param p_intStatus Vartotojo status
    @param p_strClassName Nuorodos klasės pavadinimas
    @returns HTML element
*/
function g_obj_fGetUserLinkCustomContentSource(p_strId, p_strContent, p_intStatus, p_strClassName)
{
    if (p_intStatus == 2 || p_intStatus == 3)
    {
        return p_strContent;
    }
    else
    {
        var strSource = '<a href="profile.aspx?uid=' + p_strId + '" class="' + p_strClassName + '">' + p_strContent + '</a>';
        return strSource;
    }
}

//<><><>////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////                                                 ///////////////
////////////////          Baigiamieji sharedų nustatymai         ///////////////
////////////////                                                 ///////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

function _config()
{
	addEvent(document, 'contextmenu', _contextMenu);
	addEvent(document, 'selectstart', _select);
}	
function _contextMenu(){return(true);}	// Ijungia/atjungia desine peles knopke
function _select(){return(false);}		// Ijungia/atjungia selectinima
//---------------------------------------------------------------
addEvent(window, 'unload', g_fUninitShared);
function g_fUninitShared(e)
{
    removeEvent(document, 'contextmenu', _contextMenu);
	removeEvent(document, 'selectstart', _select);
    removeEvent(window, 'unload', g_fUninitShared);
}
addEvent(document, 'help', g_fStopEvent);

/**
    History managerio paleidimas
*/
function g_fApplicationStart()
{
    if (typeof g_objHistoryManager != 'undefined' && g_objHistoryManager != null)
        g_objHistoryManager.g_fStart();
}

// Baigiamieji sharedų nustatymai \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

//<><><>////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////                                                 ///////////////
////////////////  Senos funkcijos, kurių reiktų nebenaudoti      ///////////////
////////////////                                                 ///////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
function _false(e)
{
	if(e.preventDefault)e.preventDefault();
	e.cancelBubble = true; 
	return(false); 
}

// Senos funkcijos, kurių reiktų nebenaudoti \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

/*
    Pakeičia standartio browse mygtuko stilių.
    
    @param p_strId paduodamas asp:FileUpload id.
*/
function g_fReplaceBrowseButton(p_strId)
{
    if (document.getElementById(p_strId))
    {
        var objParent = document.getElementById(p_strId).parentNode;
        document.getElementById(p_strId).className = 'file input';
        var objDiv = document.createElement('DIV');
        objDiv.className = 'fileinputs';
        objDiv.appendChild(document.getElementById(p_strId));
        objParent.appendChild(objDiv);
        var objFakeInput = document.createElement('INPUT');
        objFakeInput.type = 'text';
        objFakeInput.className = 'input fakeinput';
        objFakeInput.id = p_strId + '_fakeInput';
        objFakeInput.readOnly = 'readonly';
        objDiv.appendChild(objFakeInput);
        var objFakeBrowse = document.createElement('DIV');
        objFakeBrowse.className = 'fakebrowse';
        objFakeBrowse.id = p_strId + '_fakeBrowse';
        objFakeBrowse.innerHTML = objLang.g_str_fGetString('browse');
        objDiv.appendChild(objFakeBrowse);
        addEvent(document.getElementById(p_strId), 'change', fChange);
        addEvent(document.getElementById(p_strId + '_fakeInput'), 'focus', fSelectAll);
        document.getElementById(p_strId).value = '';
        if (cIE)
        {
            document.getElementById(p_strId + '_fakeBrowse').style.left = document.getElementById(p_strId).clientWidth + 5 + 'px';
            document.getElementById(p_strId + '_fakeBrowse').style.top = '1px';
            document.getElementById(p_strId + '_fakeInput').style.top = '1px';
            document.getElementById(p_strId + '_fakeInput').style.width = document.getElementById(p_strId).clientWidth + 'px';
            document.getElementById(p_strId + '_fakeInput').style.height = document.getElementById(p_strId).clientHeight + 'px';
        }
        else if (cFF)
        {
            document.getElementById(p_strId + '_fakeBrowse').style.left = document.getElementById(p_strId).clientWidth - 65 + 'px';
            document.getElementById(p_strId + '_fakeInput').style.width = document.getElementById(p_strId).clientWidth - 68 + 'px';
            document.getElementById(p_strId + '_fakeInput').style.height = document.getElementById(p_strId).clientHeight - 4 + 'px';
        }
    }
    
    function fChange()
    {
        document.getElementById(p_strId + '_fakeInput').value = document.getElementById(p_strId).value;
    }
    
    function fSelectAll()
    {
        document.getElementById(p_strId + '_fakeInput').select();
    }
}

/*
    Suformuoja nuorodą į skype būsenos ikonėlę.
    
    @param p_strSkypeUser skype vartotojo vardas.
*/
function g_obj_fGetSkypeImage(p_strSkypeUser)
{
    var cHIDE = false;
    if (cHIDE)
        return '<img src="' + cSYS.cIMAGE_PATH + '16_empty.gif' + '">';
    else
    {
        if (p_strSkypeUser && p_strSkypeUser.length > 0)
            return '<a href="skype:' + p_strSkypeUser + '" onclick="return skypeCheck();"><img title="' + p_strSkypeUser + '" border="0" src="http://mystatus.skype.com/smallicon/' + p_strSkypeUser + '"></a>';
        else
            return '<img src="' + cSYS.cIMAGE_PATH + '16_empty.gif' + '">';
    }
}

function g_str_fGetSkypeImage(p_strSkypeUser)
{
    var cHIDE = false;
    if (cHIDE)
        return cSYS.cIMAGE_PATH + '16_empty.gif';
    else
        return 'http://mystatus.skype.com/smallicon/' + p_strSkypeUser;
}

/**
    
*/
function g_fSetMaxLength(p_objInput, p_intMaxLength)
{
    var newAttr = document.createAttribute("maxLength");
    newAttr.nodeValue = p_intMaxLength;
    
    p_objInput.setAttributeNode(newAttr);
    //debugger;
    if (cFF)
    {
        addEvent(p_objInput, 'input', fPreventInput, p_objInput);
        addEvent(p_objInput, 'dragdrop', fIEDelay); 
    }
    if (cIE)
    {
        addEvent(p_objInput, 'keydown', fPreventInput, p_objInput);
        addEvent(p_objInput, 'drop', fIEDelay);
        addEvent(p_objInput, 'paste', fIEDelay);
    }
}
//--------------------------------------------------------------------

/**
    
*/
function fIEDelay(p_objEvent)
{
    var objTextArea = getSrcElement(p_objEvent);
    var objCaller = new clsFunctionCaller(fPreventInput, objTextArea, 0);
    objCaller.g_fStartCounter();
}
//--------------------------------------------------------------------

/**
    
*/
function fPreventInput()
{
    var intLength = this.value.length;
    if(parseInt(intLength) > parseInt(this.getAttribute('maxLength')))
    {
        g_fSetValidationMessages(this, null, this.parentNode, 'too_long', this.getAttribute('maxLength') + ' ' + objLang.g_str_fGetString('simbols_allowed'))
    }
    else
    {
        g_fRemoveValidationMessages(this);
    }
}
//--------------------------------------------------------------------

/**
    
*/
function g_fSetMaxLengthWC(p_objInput, p_intMaxLength, p_fOnValidation, p_objCont)
{
    if(!p_objCont)
    {
        g_fSetMaxLength(p_objInput, p_intMaxLength);
    }
    
    p_objCont.blnValidTextArea = true;
    
    var newAttr = document.createAttribute("maxLength");
    newAttr.nodeValue = p_intMaxLength;
    p_objCont._objMaxLenghtInput = p_objInput;
    p_objCont._fMaxLenghtFunction = p_fOnValidation;
    
    
    p_objInput.setAttributeNode(newAttr);
    //debugger;
    if (cFF)
    {
        addEvent(p_objInput, 'input', fPreventInputWC, p_objCont);
        addEvent(p_objInput, 'dragdrop', fIEDelayWC, p_objCont); 
    }
    if (cIE)
    {
        addEvent(p_objInput, 'keydown', fPreventInputWC, p_objCont); 
        addEvent(p_objInput, 'drop', fIEDelayWC, p_objCont);
        addEvent(p_objInput, 'paste', fIEDelayWC, p_objCont);
    }
}
//--------------------------------------------------------------------

/**
    
*/
function fIEDelayWC(p_objEvent)
{
    p_objEvent = p_objEvent.event;
    var objTextArea = getSrcElement(p_objEvent);
    var objCaller = new clsFunctionCaller(fPreventInputWC, this, 0);
    objCaller.g_fStartCounter();
}
//--------------------------------------------------------------------

/**
    
*/
function fPreventInputWC()
{
    //debugger;
    var objInput = this._objMaxLenghtInput;
    var objFunc = this._fMaxLenghtFunction;
    var intLength = objInput.value.length;
    
    if(parseInt(intLength) > parseInt(objInput.getAttribute('maxLength')))
    {
        if(this.blnValidTextArea)
        {
            g_fSetValidationMessages(objInput, null, objInput.parentNode, 'too_long', objInput.getAttribute('maxLength') + ' ' + objLang.g_str_fGetString('simbols_allowed'))
            this._fMaxLenghtFunction(false);
            this.blnValidTextArea = false;
        }
    }
    else
    {
        if(!this.blnValidTextArea)
        {
            g_fRemoveValidationMessages(objInput);
            this._fMaxLenghtFunction(true);
            this.blnValidTextArea = true;
        }
    }
}
//--------------------------------------------------------------------

/**
    Uzkrauna pagrindinius tinyMCE settingus
*/

function g_fLoadTinyMCE_GZ()
{
    tinyMCE_GZ.init({
    plugins : 'style,layer,table,save,advhr,advimage,advlink,emotions,iespell,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,imagemanager',
    themes : 'simple,advanced',
    languages : objLang.g_str_fGetString('language_tag').toLowerCase(),
    disk_cache : true,
    debug : false
    });
}

//--------------------------------------------------------------------

/**
    Uzkrauna tinyMCE, skirta mailui
    @param p_strParentId textarea id
*/

function g_fLoadMailTinyMCE(p_strParentId)
{
    tinyMCE.init({
        mode : "exact",
        elements : p_strParentId,
        theme : "advanced",
        language : objLang.g_str_fGetString('language_tag').toLowerCase(),
        theme_advanced_buttons1 : "bold,italic,underline,fontselect,fontsizeselect,forecolor,separator,bullist,numlist,separator,outdent,indent,separator,justifyleft,justifycenter,justifyright,separator,link,unlink,separator", 
        theme_advanced_buttons2 : "", 
        theme_advanced_buttons3 : "",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_resize_horizontal : true,
        theme_advanced_resizing : true,
        apply_source_formatting : true,
        entity_encoding: 'raw',
        relative_urls : false,
        valid_elements : "@[id|class|style|title|dir<ltr?rtl|lang|xml::lang|onclick|ondblclick|"
+ "onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|"
+ "onkeydown|onkeyup],a[rel|rev|charset|hreflang|tabindex|accesskey|type|"
+ "name|href|target|title|class|onfocus|onblur],strong/b,em/i,strike,u,"
+ "#p[align],-ol[type|compact],-ul[type|compact],-li,br,img[longdesc|usemap|"
+ "src|border|alt=|title|hspace|vspace|width|height|align],-sub,-sup,"
+ "-blockquote,-table[border=0|cellspacing|cellpadding|width|frame|rules|"
+ "height|align|summary|bgcolor|background|bordercolor],-tr[rowspan|width|"
+ "height|align|valign|bgcolor|background|bordercolor],tbody,thead,tfoot,"
+ "#td[colspan|rowspan|width|height|align|valign|bgcolor|background|bordercolor"
+ "|scope],#th[colspan|rowspan|width|height|align|valign|scope],caption,-div,"
+ "-span,-code,-pre,address,-h1,-h2,-h3,-h4,-h5,-h6,hr[size|noshade],-font[face"
+ "|size|color],dd,dl,dt,cite,abbr,acronym,del[datetime|cite],ins[datetime|cite],"
+ "object[classid|width|height|codebase|id|*],param[name|value|_value],embed[type|width"
+ "|height|src|*],script[src|type],map[name],area[shape|coords|href|alt|target],bdo,"
+ "button,col[align|char|charoff|span|valign|width],colgroup[align|char|charoff|span|"
+ "valign|width],dfn,fieldset,form[action|accept|accept-charset|enctype|method],"
+ "input[accept|alt|checked|disabled|maxlength|name|readonly|size|src|type|value],"
+ "kbd,label[for],legend,noscript,optgroup[label|disabled],option[disabled|label|selected|value],"
+ "q[cite],samp,select[disabled|multiple|name|size],small,"
+ "textarea[cols|rows|disabled|name|readonly],tt,var,big"
    });
}

//--------------------------------------------------------------------

/**
    Uzkrauna tinyMCE, skirta straipsniu rasymui
    @param p_strParentId textarea id
    @param p_strFunction failu pasirinkimo tvarkymo funkcijos pavadinimas
*/

function g_fLoadArticlesTinyMCE(p_strParentId, p_strFunction)
{
    tinyMCE.init({
        mode : "exact",
        elements : p_strParentId,
        theme : "advanced",
        language : objLang.g_str_fGetString('language_tag').toLowerCase(),
        plugins : "preview,insertdatetime,emotions,iespell,advhr,media,print,contextmenu,table",
        theme_advanced_buttons1 : "bold,italic,underline,fontselect,fontsizeselect,formatselect,forecolor,backcolor,separator,bullist,numlist,separator,outdent,indent,separator,justifyleft,justifycenter,justifyright,separator,link,unlink,separator",
        theme_advanced_buttons2 : "cut,copy,paste,separator,undo,redo,separator,anchor,image,code,separator,insertdate,inserttime,preview,separator,removeformat,separator,charmap,emotions,iespell,media,advhr,separator,print,separator,cleanup,separator,tablecontrols,table,row_props,cell_props,delete_col,delete_row,col_after,col_before,row_after,row_before,row_after,row_before,split_cells,merge_cells,separator",
        theme_advanced_buttons3 : "",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        plugin_insertdate_dateFormat : "%Y-%m-%d",
        plugin_insertdate_timeFormat : "%H:%M:%S",
        file_browser_callback : p_strFunction,
        theme_advanced_resize_horizontal : true,
        theme_advanced_resizing : true,
        apply_source_formatting : true,
        entity_encoding: 'raw',
        relative_urls : false,
        valid_elements : "@[id|class|style|title|dir<ltr?rtl|lang|xml::lang|onclick|ondblclick|"
+ "onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|"
+ "onkeydown|onkeyup],a[rel|rev|charset|hreflang|tabindex|accesskey|type|"
+ "name|href|target|title|class|onfocus|onblur],strong/b,em/i,strike,u,"
+ "#p[align],-ol[type|compact],-ul[type|compact],-li,br,img[longdesc|usemap|"
+ "src|border|alt=|title|hspace|vspace|width|height|align],-sub,-sup,"
+ "-blockquote,-table[border=0|cellspacing|cellpadding|width|frame|rules|"
+ "height|align|summary|bgcolor|background|bordercolor],-tr[rowspan|width|"
+ "height|align|valign|bgcolor|background|bordercolor],tbody,thead,tfoot,"
+ "#td[colspan|rowspan|width|height|align|valign|bgcolor|background|bordercolor"
+ "|scope],#th[colspan|rowspan|width|height|align|valign|scope],caption,-div,"
+ "-span,-code,-pre,address,-h1,-h2,-h3,-h4,-h5,-h6,hr[size|noshade],-font[face"
+ "|size|color],dd,dl,dt,cite,abbr,acronym,del[datetime|cite],ins[datetime|cite],"
+ "object[classid|width|height|codebase|*],param[name|value|_value],embed[type|width"
+ "|height|src|*],script[src|type],map[name],area[shape|coords|href|alt|target],bdo,"
+ "button,col[align|char|charoff|span|valign|width],colgroup[align|char|charoff|span|"
+ "valign|width],dfn,fieldset,form[action|accept|accept-charset|enctype|method],"
+ "input[accept|alt|checked|disabled|maxlength|name|readonly|size|src|type|value],"
+ "kbd,label[for],legend,noscript,optgroup[label|disabled],option[disabled|label|selected|value],"
+ "q[cite],samp,select[disabled|multiple|name|size],small,"
+ "textarea[cols|rows|disabled|name|readonly],tt,var,big"
   
    });    
     
}

//--------------------------------------------------------------------

function g_str_fParseTemplate(p_strTemplateString, p_hshContext)
{
    for (var strItem in p_hshContext)
    {
        p_strTemplateString = p_strTemplateString.replace(new RegExp('\\${' + strItem + '}', 'g'), p_hshContext[strItem]);
    }
    return p_strTemplateString;
}