﻿        
        
       /// var BasePath = window.location.protocol + '//' + window.location.host + '/';
        var currentForTest = null;
        var currentForTestSender = null;
        var hAdded = false;
        function setMultiListOver(sender, suppressShowing)
        {
            var parent = sender.parentMultiList;
            var container;
            var header;
            var block;
            var selectionInPopup;
            var selectionInCaption;
            if(!parent)
            {
                parent = sender;
                while(parent != null && parent.getAttribute('multilistcontrol') != '1')
                {
                    parent = parent.parentNode;
                }
                
                sender.parentMultiList = parent;
                
                var subitems = parent.getElementsByTagName('DIV');
                for(var i = 0; i < subitems.length; i++)
                {
                    if(subitems[i].getAttribute && subitems[i].getAttribute('multilistblock') == '1')
                    {
                        block = subitems[i];
                        
                        for(var i = 0; i < document.forms[0].childNodes.length; i++)
                        {
                            var el = document.forms[0].childNodes[i];
                            if(el.getAttribute && el.getAttribute('multilistblock') == '1' && el.senderMultiList.parentMultiList.id == parent.id)
                            {
                                document.forms[0].removeChild(el);
                                break;
                            }
                        }
                        
                        var subitems2 = block.getElementsByTagName('div');
                        for(var j = 0; j < subitems2.length; j++)
                        {
                            if(subitems2[j].getAttribute)
                            {
                                if(subitems2[j].getAttribute('multilisthead') == '1')
                                {
                                    header = subitems2[j];
                                }
                                else if(subitems2[j].getAttribute('multilistcontrolcont') == '1')
                                {
                                    container = subitems2[j];
                                }
                                else if(subitems2[j].getAttribute('multilistsel') == '1')
                                {
                                    selectionInPopup = subitems2[j];
                                }
                            }
                        }
                    }
                    else if(subitems[i].getAttribute && subitems[i].getAttribute('multilistcaption') == '1')
                    {
                        selectionInCaption = subitems[i];
                    }
                }
                
                block.containerMultiList = container;
                block.headerMultiList = header;
                block.senderMultiList = sender;
                block.parentMultiList = parent;
                
                container.headerMultiList = header;
                container.senderMultiList = sender;
                container.parentMultiList = parent;
                
                parent.blockMultiList = block;
                parent.headerMultiList = header;
                parent.senderMultiList = sender;
                parent.containerMultiList = container;
                parent.selectionInPopup = selectionInPopup;
                parent.selectionInCaption = selectionInCaption;
                parent.hdnMultiList = parent.getElementsByTagName('input')[0];
                
                var contA = container.getElementsByTagName('a');
                parent.mlItems = new Array();
                parent.selectedMlItems = new Array();
                for(var i = 0; i < contA.length; i++)
                {
                    if(contA[i].getAttribute && contA[i].getAttribute('ml') == '1')
                    {
                        contA[i].parentMultiList = parent;
                        parent.mlItems.push(contA[i]);
                        
                        if(contA[i].getAttribute('ml_sel') == '1')
                            parent.selectedMlItems.push(contA[i]);
                        
                    }
                    contA[i].iIndex = i;
                }
                
                if(parent.selectionInPopup)
                {
                    var contSelA = parent.selectionInPopup.getElementsByTagName('a');
                    for(var i = 0; i < contSelA.length; i++)
                    {
                        if(contSelA[i].getAttribute && contSelA[i].getAttribute('ml_rel'))
                        {
                            contSelA[i].relatedItem = parent.mlItems[contSelA[i].getAttribute('ml_rel')];
                        }
                    }
                }
                if(parent.selectionInCaption)
                {
                    var contSelA = parent.selectionInCaption.getElementsByTagName('a');
                    for(var i = 0; i < contSelA.length; i++)
                    {
                        if(contSelA[i].getAttribute && contSelA[i].getAttribute('ml_rel'))
                        {
                            contSelA[i].relatedItem = parent.mlItems[contSelA[i].getAttribute('ml_rel')];
                        }
                    }
                }
            }
            else
            {
                //container = sender.parentMultiList.containerMultiList;
                block = sender.parentMultiList.blockMultiList;
            }
            
            if(currentForTest != null)
            {
                if(currentForTest == block)
                {
                    closeCurrentMultilist();
                    return;
                }
                else
                    currentForTest.style.display = 'none';
            }
                
            currentForTest = block;
            currentForTestSender = sender;
            
            if(!hAdded)
            {
                hAdded = true;
                AddBrowserHandler(document, 'mousedown', mi_testonhover);
                //AddBrowserHandler(document, 'mousemove', mi_testonhover);
                AddBrowserHandler(window, 'resize', mi_onposition);
                AddBrowserHandler(window, 'scroll', mi_onposition);
            }
            
            if(!suppressShowing)
            {
                document.forms[0].appendChild(currentForTest);
                    
                setMultilistItemPosition(currentForTest, sender, 16, null,  true, true);
            }
        }
        
        function setMultilistItemPosition(obj, parent, iTop, iLeft, toShow, toSize)
        {
            if(!iLeft)
            {
                if(parent.parentMultiList.getAttribute('shiftl'))
                    iLeft = parseInt(parent.parentMultiList.getAttribute('shiftl'));
                    
                if(!iLeft || isNaN(iLeft))
                    iLeft = 20;
            }
            
            var _xOffs = 0;
            var _yOffs = 0;

            var _obj = parent;
                    
            while(_obj != null)
            {
                if(_obj.offsetLeft != null)
                    _xOffs += _obj.offsetLeft;
                    
                if(_obj.offsetTop != null)
                    _yOffs += _obj.offsetTop;
                
                _xOffs -= _obj.scrollLeft;
                _yOffs -= _obj.scrollTop;
                
                _obj = _obj.offsetParent;
            }
            
            var _windowTop = 0;
            var _windowLeft = 0;
            
            if( typeof( window.pageYOffset ) == 'number' ) {
              //Netscape compliant
              _windowTop = window.pageYOffset;
              _windowLeft = window.pageXOffset;
            } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
              //DOM compliant
              _windowTop = document.body.scrollTop;
              _windowLeft = document.body.scrollLeft;
            } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
              //IE6 standards compliant mode
              _windowTop = document.documentElement.scrollTop;
              _windowLeft = document.documentElement.scrollLeft;
            }

            var cont = obj;
            cont.style.top = '' + (_yOffs + iTop + _windowTop) + 'px';
            cont.style.left = '' + (_xOffs - (ie ? 0 : 1) + iLeft + _windowLeft) + 'px';
            

            if(toShow)
            {
                cont.style.display = 'block';
                if(parent.parentMultiList.getAttribute('OnClientListOpened')){
                    window.setTimeout(parent.parentMultiList.getAttribute('OnClientListOpened') + '()', 0);}
            }

            var yTo = cont.offsetHeight;
            setActualHeight(parent.parentMultiList.containerMultiList, yTo - parent.parentMultiList.headerMultiList.offsetHeight - 16);

            if(toSize)
            {
                cont.style.height = '1px';
                actM.addAction(new action(cont, 1, yTo, 'height', 150, -100, null, null, 15));
            }
        }
        
        function mi_onposition(e)
        {
            if(!currentForTest)
                {return true;}
            setMultilistItemPosition(currentForTest, currentForTestSender, 16, null,  true);
        }
        
        //var testStarted = false;
        function mi_testonhover(e)
        {
            if(!currentForTest)
                {return true;}
            
            var p = (e && e.target ? e.target : event.srcElement);
            
            while(p != null && p != currentForTest && p != currentForTestSender)
            {
                p = p.parentNode;
                //testStarted = null;
            }
            
            if(!p)
            {
                closeCurrentMultilist();
                //testStarted = currentForTest;
                //window.setTimeout('testForHide();', 1000);
            }
        }
        function closeCurrentMultilist()
        {
            if(currentForTest)
            {
                currentForTest.style.display = 'none';
                if(currentForTestSender.parentMultiList.getAttribute('OnClientListClosed'))
                    window.setTimeout(currentForTestSender.parentMultiList.getAttribute('OnClientListClosed') + '()', 0);
            }
            currentForTest = null;
        }
        /*
        function testForHide()
        {
            if(testStarted == currentForTest)
            {
                testStarted = null;
                
                if(currentForTest)
                    currentForTest.style.display = 'none';
                currentForTest = null;
            }
        }*/
        
        function closeMultiList(sender)
        {
            closeCurrentMultilist();
        }
        
        function clearMultiList(sender, senderIsParent)
        {
            var cont = senderIsParent ? sender.containerMultiList : sender.parentNode.parentNode.parentNode;
            
            if(!cont || !cont.parentMultiList)
            {
                setMultiListOver(sender, true);
                cont = senderIsParent ? sender.containerMultiList : sender.parentNode.parentNode.parentNode;
            }
            
            var items = cont.parentMultiList.selectedMlItems;
            while(items.length > 0)
            {
                ml_set(items[0], true);
            }
                        
            updateMlElementsState(cont);
        }
        
        function getMultilistValues(container)
        {
            var mValues = new Array();
            
            for (var i = 0; i < container.containerMultiList.parentMultiList.mlItems.length; i++)
            {
                var it = container.containerMultiList.parentMultiList.mlItems[i];
                if(getMlElementState(it))
                    mValues.push(it.getAttribute('ml_val'))
            }
            
            return mValues;
        }

        function setMultilistValues(container, values)
        {
            if(!container.parentMultiList)
                setMultiListOver(container, true);
                
            clearMultiList(container, true);
             
            if(values)
            {
                var arr;
                if(typeof(values) == Array)
                {
                    arr = value;
                }
                else
                {
                    arr = new Array();
                    arr.push(values);
                }
                
                for (var i = 0; i < values.length; i++)
                {                    
                    for (var j = 0; j < container.containerMultiList.parentMultiList.mlItems.length; j++)
                    {
                        var it = container.containerMultiList.parentMultiList.mlItems[j];
                        
                        if(it.getAttribute('ml_val') == values[i])
                        {
                            ml_set(it, true);
                            break;
                        }
                    }
                }
            }
                        
            updateMlElementsState(container.containerMultiList);
        }
        
        function ml_set(sender, suppressUpdating)
        {
            var bSel = !getMlElementState(sender); // by default
            sender.ml_sel = bSel;
            
            sender.className = bSel ? 'ml_sel' : '';
            
            if(bSel)
            {
                var iMax = parseInt(sender.parentMultiList.getAttribute('maxselecteditems'));
                
                if(!isNaN(iMax) && iMax > 0 && sender.parentMultiList.selectedMlItems.length == iMax)
                {
                    ml_set(sender.parentMultiList.selectedMlItems[0], true);
                }
                sender.parentMultiList.selectedMlItems.push(sender);
                
                if(sender.parentMultiList.selectionInPopup)
                {
                    var sp = document.createElement('a');
                    
                    sp.relatedItem = sender;
                    
                    sp.title = 'remove';
                    sp.setAttribute('ml', '1');
                    sp.href = '#';
                    sp.onclick = ml_sel_set;
                    sp.className = 'ml_sel';
                    sp.setAttribute('ml_rel', sender.iIndex);
                    sp.innerHTML = sender.innerHTML;
                    
                    sp.style.backgroundImage = sender.style.backgroundImage;
                        //writer.Write("<span class='separator'><span>;</span></span>");
                    var sps = sender.parentMultiList.selectionInPopup.getElementsByTagName('span');
                    sender.parentMultiList.selectionInPopup.insertBefore(sp, sps.length == 0 ? null : sps[sps.length - 1]);
                }
                if(sender.parentMultiList.selectionInCaption)
                {
                    var sp = document.createElement('a');

                    sp.relatedItem = sender;

                    sp.title = 'remove';
                    sp.setAttribute('ml', '1');
                    sp.href = '#';
                    sp.onclick = ml_sel_set;
                    sp.className = 'ml_sel';
                    sp.setAttribute('ml_rel', sender.iIndex);
                    sp.innerHTML = sender.innerHTML + "<span class='separator'><span>;</span></span>";
                    
                    sp.style.backgroundImage = sender.style.backgroundImage;
                    
                    var sps = sender.parentMultiList.selectionInCaption.getElementsByTagName('span');
                    sender.parentMultiList.selectionInCaption.insertBefore(sp, sps.length == 0 ? null : sps[sps.length - 1]);
                }
            }
            else
            {
                remove_ml_sel(sender.parentMultiList, sender.iIndex);
                for(var i = 0; i < sender.parentMultiList.selectedMlItems.length; i++)
                {
                    if(sender.parentMultiList.selectedMlItems[i] == sender)
                    {
                        sender.parentMultiList.selectedMlItems.splice(i, 1);
                        break;
                    }
                }
            }
            
            if(!suppressUpdating)
                updateMlElementsState(sender);
        }
        
        function ml_sel_set(e)
        {
            var sender = (e && e.target ? e.target : event.srcElement);
            var rel = sender.relatedItem;
            
            if(!rel) // when the multilist wasn't shown before and we pressing selected in caption link
            {
                setMultiListOver(sender.parentNode, true);
                rel = sender.relatedItem;
            }
                
            ml_set(rel);
            
            return false;
        }
        
        function remove_ml_sel(parent, iIndex)
        {
            if(parent.selectionInPopup)
            {
                var items = parent.selectionInPopup.getElementsByTagName('a');
                for(var i = 0; i < items.length; i++)
                {
                    if(items[i].getAttribute('ml_rel') == iIndex)
                    {
                        items[i].parentNode.removeChild(items[i]);
                        break;
                    }
                }
            }
            if(parent.selectionInCaption)
            {
                var items = parent.selectionInCaption.getElementsByTagName('a');
                for(var i = 0; i < items.length; i++)
                {
                    if(items[i].getAttribute('ml_rel') == iIndex)
                    {
                        items[i].parentNode.removeChild(items[i]);
                        break;
                    }
                }
            }
        }
        
        function getMlElementState(item)
        {
            if(item.ml_sel == true)
                return true;
            else if(item.ml_sel == false)
                return false;
            else if(item.getAttribute('ml_sel') == '1')
                return true;
            else
                return false;
        }
        
        function updateMlElementsState(sender)
        {
            var sValue = '';
            var sText = '';
            
            var parent = sender.parentMultiList;
            var currElem;
            for(var i = 0; i < parent.mlItems.length; i++)
            {
                currElem = parent.mlItems[i];
                if(getMlElementState(currElem))
                {
                    sValue += i + ';';
                    sText += (sText == '' ? '' : ' ') + currElem.innerHTML + ';';
                }
            }
            
            parent.hdnMultiList.value = sValue;
            //if(sender.parentMultiList.getAttribute('dispincapt') == '1')
            //    parent.senderMultiList.innerHTML = sText == '' ? ('&lt;' + (sender.parentMultiList.getAttribute('emptytext') ? sender.parentMultiList.getAttribute('emptytext') : 'select') + '&gt;')  : sText;
                
            if(sender.parentMultiList.getAttribute('selectionintooltip') != 'false')
                parent.senderMultiList.title = sText;
                
            if(sender.parentMultiList.getAttribute('onclientchange'))
            {
                var fOnChange = eval(sender.parentMultiList.getAttribute('onclientchange'));
                fOnChange(sender.parentMultiList);
            }
                
            setMultilistItemPosition(currentForTest ? currentForTest : parent.blockMultiList, currentForTestSender ? currentForTestSender : sender, 16, null, false, false);
        }
        

    // item instruments        
    function itemUploadedAuto(uploadParams)
    {
        $get(uploadParams.senderID).getElementsByTagName('input')[0].value = uploadParams.fileNewName;
        var items = $get(uploadParams.senderID).getElementsByTagName('a');
        for(var i = 0; i < items.length; i++)
        {
            if(items[i].getAttribute('remover') == 'true')
            {   
                items[i].style.display = '';
                break;
            }
        }
    }
    function removeItemAuto(senderID, sender)
    {
        var cont = $get(senderID);
        cont.getElementsByTagName('input')[0].value = '-1';
        
        if(sender)
            sender.style.display = 'none';

        var items = cont.getElementsByTagName('a');
        for(var i = 0; i < items.length; i++)
        {
            if(items[i].getAttribute('downloader') == '1' || items[i].getAttribute('remover') == '1' || items[i].getAttribute('remover') == 'true')
                items[i].style.display = 'none';
        }
    }
    
    function uploadPictureEx(sender, title, exts, callBackHandler)
    {
        openUploadDialog(title ? title : 'Upload Picture', exts ? exts : 'png|jpg|jpeg|gif', callBackHandler ? callBackHandler : photoUploaded, sender.parentNode.id, '');
    }
    
    function uploadLyricsFromEdit(sender)
    {
        openUploadDialog('Upload Song Lyrics', 'doc|docx|txt', lyricsUploaded, sender.parentNode.id, '');
    }
    
//     function openUploadDialog(title, filesExts, callBackHandler, senderID, progressID)
//  { 
//    var pnlCore = $get('pnlUploadPopupCore2.ClientID'); 
//    if(pnlCore) 
//        pnlCore.style.display = 'none'; 
//        
//    $get('pnlUploadLD.ClientID').style.display = ''; 
//    var pnl = $get('pnlUpload.ClientID'); 
//    pnl.callBackHandler = callBackHandler; 
//    pnl.senderID = senderID; 
//    if(title) { pnl.headerBar.innerHTML = title; } 
//    pnl.showAndSubmit('load;' + filesExts + ';' + senderID + ';' + progressID);
// }
    function lyricsUploaded(uploadParams)
    {
        $get(uploadParams.senderID).getElementsByTagName('input')[0].value = uploadParams.fileNewName;
        var items = $get(uploadParams.senderID).getElementsByTagName('a');
        for(var i = 0; i < items.length; i++)
        {
            if(items[i].getAttribute('downloader') == '1' || items[i].getAttribute('remover') == '1' || items[i].getAttribute('remover') == 'true')
                items[i].style.display = '';
        }
    }
    
    
    function downloadLyricsFromEdit(uid, sender)
    {
        var hdn = sender.parentNode.getElementsByTagName('input')[0];
        if(hdn.value == '-1')
        {
            alert('Lyrics file has been deleted. You can upload a new one.');
            return;
        }        
        else if(hdn.value != '')
        {
            alert('To be able to download uploaded lyrics files the song content must be stored first.');
            return;
        }
        else
        {
            downloadSongLyrics(uid);
        }
    }
    // photo instruments        
    function photoUploaded(uploadParams)
    {
        $get(uploadParams.senderID).getElementsByTagName('input')[0].value = uploadParams.fileNewName;
        $get(uploadParams.senderID).getElementsByTagName('img')[0].src = BasePath + 'GetImage.ashx?id=' + uploadParams.fileNewName + '&type=tmp';
    }
    function removePhoto(senderID)
    {
        $get(senderID).getElementsByTagName('input')[0].value = '-1';
        $get(senderID).getElementsByTagName('img')[0].src = BasePath + 'GetImage.ashx?id=0&type=plsong';
    }

    // additonal
    applyMatchedFormatting = function(sOriginal, sOriginalCopy, sPattern)
    {
        if(sPattern == '')
            return sOriginal;

        var sb = '';
        var i = 0;
        while (i < sOriginal.length)
        {
            var ind = sOriginalCopy.indexOf(sPattern, i);
            if (ind < 0)
            {
                sb += sOriginal.substr(i);
                break;
            }
            else
            {
                if (ind > i)
                    sb += sOriginal.substr(i, ind - i);

                sb += '<b>' + sOriginal.substr(ind, sPattern.length) + '</b>';
                i = ind + sPattern.length;
            }
        }

        return sb;
    }

    // download issues
    function downloadSongLyrics(uid)
    {
        window.open('GetDoc.ashx?id=' + uid + '&type=lr', 'docdownload');
    }
    
    function downloadUserSong(uid)
    {
        PageMethods.DownloadUserSongInit(uid, downloadUserSongOk, null, null);
    }
    
    function downloadUserSongOk(pmInfo)
    {
        var result = pmInfo.Result;
        
        if(result)
        {
            window.open('GetSong.ashx?id=' + result[0] + '&s=' + result[1] + '&dwn=1', 'songdownload');
        }
    }
    
    
    // drag-n-drop
    var DNDManager = null;
    
    function DNDManager_mousemove(e)
    {
        return DNDManager.mousemove(e);
    }
    
    function DNDManager_mouseup(e)
    {
        return DNDManager.mouseup(e);
    }
    
    function DNDManager_scroll(e)
    {
        return DNDManager.scroll(e);
    }
    
    function DragNDropManager()
    {
        this.sender;
        this.senderBase;
        
        this.container;
        this.callBackHandlerDragging;
        this.callBackHandlerDrop;
        
        this.initialized = false;
        this.manageAuto;
        
        this.mouseOffX;
        this.mouseOffY;
        
        this.containerOffX;
        this.containerOffY;
        
        this.zones;
        this.parentZone;
        this.currentHoveredZone;
        this.zoneItemTemplate;
        
        this.onStartDragging;
        this.onStopDragging;
        
        this.initialize = function()
        {
            if(!this.initialized)
            {
                this.initialized = true;
                //AddBrowserHandler(document, 'mousedown', this.mousedown);
                AddBrowserHandler(document, 'mousemove', DNDManager_mousemove);
                AddBrowserHandler(document, 'mouseup', DNDManager_mouseup);
                AddBrowserHandler(document, 'scroll', DNDManager_scroll);
            }
            
            this.zones = new Array();
            
            var zonesitems = document.getElementsByTagName('div');
            for(var i = 0; i < zonesitems.length; i++)
            {
                var it = zonesitems[i];
                if(it.getAttribute('dragndropzone'))
                {
                    var obj = new Object();
                    var offs = getElementOffset(it);
                    obj.container = it;
                    obj.x = offs.left;
                    obj.y = offs.top;
                    obj.width = it.clientWidth;
                    obj.height = it.clientHeight;
                    
                    this.zones.push(obj);
                }
            }
        }
        
        this.prepareDragging = function(params)
        {
            if(!params)
            {
                alert('Params can\'t be null.')
                return;
            }
            
            this.initialize();
            this.preparedParams = params;
            
            if(params.x == null || params.y == null)
            {
                
            }
        }
        
        this.startDragging = function(params)
        {
            if(!params)
            {
                alert('Params can\'t be null.')
                return;
            }
            
            this.initialize();
            
            if(this.sender)
            {
                this.stopDragging();
            }
            
            this.isDragging = true;

            this.sender = params.sender;
            this.senderBase = params.sender;
            
            this.container = params.container;
            this.callBackHandler = params.callBack;
            this.manageAuto = !params.manageNotAuto;
            
            this.extendedMode = params.extendedMode;
            this.dragCopy = params.dragCopy;
            
            this.onStartDragging = params.onStartDragging;
            this.onStopDragging = params.onStopDragging;
            
            this.parentZone = null;
            this.currentHoveredZone;
            if(this.zoneItemTemplate)
                this.zoneItemTemplate.style.dislay = 'none';

            var scr = getElementOffset(this.sender);
            
            if(this.extendedMode)
            {
                var p = this.sender.parentNode;
                while(p)
                {
                    if(p.getAttribute && p.getAttribute('dragndropzone'))
                    {
                        if(!p.getAttribute('allowmovingin'))
                            this.parentZone = p;
                            
                        break;
                    }
                    
                    p = p.parentNode;
                }
            }
            
            if(this.dragCopy)
            {
                var nd = this.sender.cloneNode(true);
                nd.style.position = 'absolute';
                nd.style.top = scr.top + 'px';
                nd.style.left = scr.left + 'px';
                
                SetElementTransparency(nd, 70);
                
                document.body.appendChild(nd);
                
                if(this.onStartDragging)
                {
                    var obj = new Object();
                    obj.sender = this.senderBase || this.sender;
                    obj.element = nd;
                    this.onStartDragging(obj);
                }
                
                this.sender = nd;
            }
            
            this.setContainerOff();

            this.mouseOffX = params.x || (xMousePos + scr.documentleft) - scr.left;
            this.mouseOffY = params.y || (yMousePos + scr.documenttop) - scr.top;
            
            this.processDragging(null);
        }
        
        this.mousemove = function(e)
        {
            if(this.preparedParams)
            {
                this.preparedParams.event = e || window.event;
                this.startDragging(this.preparedParams);
                this.preparedParams = null;
            }
            else this.processDragging(e);
                
            return false;
        }
        
        this.mouseup = function(e)
        {
            if(this.sender)
            {
                this.stopDragging();
            }
            this.preparedParams = null;
        }
        
        this.scroll = function(e)
        {
            this.setContainerOff();
        }
        
        this.processDragging = function(e)
        {
            if(!this.sender)
                return false;
                
            if(this.manageAuto)
            {
                var scr = getElementOffset(null, null);
                
                if(this.container)
                {
                    var _x = 0;
                    
                    var bInnerIsThinner = this.sender.offsetWidth < this.container.offsetWidth;
                    if(xMousePos + scr.documentleft - this.mouseOffX > this.containerOffX && !bInnerIsThinner
                        || bInnerIsThinner && xMousePos + scr.documentleft - this.mouseOffX < this.containerOffX)
                        _x = 0;
                    else if(xMousePos + scr.documentleft - this.mouseOffX + this.sender.offsetWidth < this.containerOffX + this.container.offsetWidth && !bInnerIsThinner ||
                        xMousePos + scr.documentleft - this.mouseOffX + this.sender.offsetWidth > this.containerOffX + this.container.offsetWidth && bInnerIsThinner)
                        _x = this.container.offsetWidth - this.sender.offsetWidth;
                    else
                        _x = (xMousePos + scr.documentleft - this.containerOffX - this.mouseOffX);

                    this.sender.style.left = _x + 'px';
                    
                    var _y = 0;
                    var bInnerIsShorter = this.sender.offsetHeight < this.container.offsetHeight;
                    if(yMousePos + scr.documenttop - this.mouseOffY > this.containerOffY && !bInnerIsShorter
                        || yMousePos + scr.documenttop - this.mouseOffY < this.containerOffY && bInnerIsShorter)
                        _y = 0;
                    else if(!bInnerIsShorter && yMousePos + scr.documenttop - this.mouseOffY + this.sender.offsetHeight < this.containerOffY + this.container.offsetHeight
                        || bInnerIsShorter && yMousePos + scr.documenttop - this.mouseOffY + this.sender.offsetHeight > this.containerOffY + this.container.offsetHeight)
                        _y = this.container.offsetHeight - this.sender.offsetHeight;
                    else
                        _y = (yMousePos + scr.documenttop - this.containerOffY - this.mouseOffY);
                    
                    this.sender.style.top = _y + 'px';
                }
                else
                {
                    this.sender.style.left = (xMousePos + scr.documentleft - /*this.containerOffX - */this.mouseOffX) + 'px';
                    this.sender.style.top = (yMousePos + scr.documenttop - /*this.containerOffY - */this.mouseOffY) + 'px';
                    
                    if(this.extendedMode)
                    {
                        var currZone;
                        for(var i = 0; i < this.zones.length; i++)
                        {
                            var it = this.zones[i];
                            if(xMousePos > it.x && xMousePos < it.x + it.width
                                && yMousePos > it.y && yMousePos < it.y + it.height)
                            {
                                currZone = it;
                                break;
                            }
                        }
                        
                        if(currZone != this.currentHoveredZone)
                        {
                            if(this.currentHoveredZone)
                            {
                                Extensions.RemoveCssClass(this.currentHoveredZone.container, 'GZoneHovered');
                            }
                            
                            this.currentHoveredZone = currZone;
                            if(this.currentHoveredZone)
                                Extensions.AddCssClass(this.currentHoveredZone.container, 'GZoneHovered');
                        }
                        
                        if(this.currentHoveredZone)
                        {
                            if(this.zoneItemTemplate)
                            {
                                RemoveNodeEx(this.zoneItemTemplate);
                                this.zoneItemTemplate = null;
                            }
                            
                            if(!this.zoneItemTemplate)
                            {
                                this.zoneItemTemplate = document.createElement('div');
                                this.zoneItemTemplate.className = 'GZoneItemTemplate';
                            }
                            else this.zoneItemTemplate.style.display = '';
                            //if(this.currentHoveredZone.container != this.zoneItemTemplate.parentNode)
                            //{
                                var items = Extensions.GetChildNodes(this.currentHoveredZone.container);
                                var insertBeforeElement = null;
                                var z = null;
                                if(items.length > 0)
                                {
                                    var it = items[0];
                                    var w = it.offsetWidth + Extensions.GetCssProperty(it, 'marginLeft', true) + Extensions.GetCssProperty(it, 'marginRight', true);
                                    var h = it.offsetHeight + Extensions.GetCssProperty(it, 'marginTop', true) + Extensions.GetCssProperty(it, 'marginBottom', true);
                                    var dx = xMousePos - this.currentHoveredZone.x;// - this.currentHoveredZone.container.scrollTop;
                                    var dy = yMousePos - this.currentHoveredZone.y;// - this.currentHoveredZone.container.scrollLeft;
                                    var k = Math.round(this.currentHoveredZone.width / w -0.5);
                                    var n = Math.round(dy / h - 0.5);
                                    z = n * k + Math.round(dx / w - 0.5);
                                    if(z < items.length)
                                        insertBeforeElement = items[z];
                                }
                                
                                if(!insertBeforeElement)
                                {
                                    this.currentHoveredZone.container.insertBefore(this.zoneItemTemplate, null);
                                }
                                else
                                {
                                    if(insertBeforeElement == (this.senderBase || this.sender) || z != null && z - 1 > 0 && items[z - 1] == (this.senderBase || this.sender))
                                        this.zoneItemTemplate.style.display = 'none';
                                    else
                                        this.currentHoveredZone.container.insertBefore(this.zoneItemTemplate, insertBeforeElement);
                                }
                                
                                this.currentItemIndexInZone = z;
                                
                            //}
                        }
                        else
                        {
                            if(this.zoneItemTemplate)
                                this.zoneItemTemplate.style.display = 'none';
                        }
                    }
                }
            }
            
            if(this.callBackHandler)
            {
                this.callBackHandler(e, this.sender);
            }
        }
        
        this.setContainerOff = function()
        {
            if(this.container)
            {
                var containerOffsets = getElementOffset(this.container);
                this.containerOffX = containerOffsets.left;
                this.containerOffY = containerOffsets.top;
            }
            else
            {
                this.containerOffX = 0;
                this.containerOffY = 0;
            }
        }
        
        this.stopDragging = function()
        {
            if(this.onStopDragging)
            {
                try
                {
                    var obj = new Object();
                    obj.sender = this.senderBase || this.sender;
                    if(this.currentHoveredZone)
                    {
                        obj.zone = this.currentHoveredZone.container;
                        obj.index = this.currentItemIndexInZone;
                    }
                    this.onStopDragging(obj);
                }catch(er){}
            }
            
            if(this.zoneItemTemplate)
                RemoveNodeEx(this.zoneItemTemplate);
            if(this.currentHoveredZone)
                Extensions.RemoveCssClass(this.currentHoveredZone.container, 'GZoneHovered');
            this.zoneItemTemplate = null;
            this.currentHoveredZone = null;
            
            if(this.dragCopy)
            {
                RemoveNodeEx(this.sender);
            }
            
            this.isDragging = false;
            
            this.sender = null;
            this.preparedParams = null;
        }
    }
    
    DNDManager = new DragNDropManager();
    
    
    
    var MManager = null;
    function MoveHoverManager()
    {
        this.handlers = new Array();
        this.hovered = new Array();
        
        this.hTypeHover = 0;
        this.hTypeClick = 1;

        this.addClassHandler = function (className, handlerIn, handlerOut, hoverClassName, iInDelay, iOutDelay, fnInDelay)
        {
            this.addHandler(className, null, null, null, handlerIn, handlerOut, hoverClassName, this.hTypeHover, null, { inDelay : iInDelay, outDelay : iOutDelay, fnInDelay : fnInDelay });
        }
        
        this.addIdHandler = function(controlID, notStrong, handlerIn, handlerOut)
        {
            this.addHandler(null, controlID, notStrong, null, handlerIn, handlerOut, null, this.hTypeHover);
        }
        
        this.addContainerHandler = function(control, handlerIn, handlerOut)
        {
            this.addHandler(null, null, null, control, handlerIn, handlerOut, null, this.hTypeHover);
        }
        
        this.addClickHandler = function(control, handlerClick, controlClassName)
        {
            this.addHandler(controlClassName, null, null, control, null, null, null, this.hTypeClick, handlerClick);
        }
        this.click = this.addClickHandler;
        this.cls = this.addClassHandler;
        this.cl = this.addClassHandler; // obsolete

        this.addHandler = function (className, controlID, notStrong, control, handlerIn, handlerOut, hoverClassName, handlerType, handlerClick, params)
        {
            var obj = new Object();
            obj.className = className;
            obj.controlID = controlID;
            obj.notStrong = notStrong;
            obj.control = control;
            obj.handlerIn = handlerIn;
            obj.handlerOut = handlerOut;
            obj.hoverClassName = hoverClassName;

            obj.handlerClick = handlerClick;
            obj.handlerType = handlerType;

            obj.params = params || new Object();

            this.handlers.push(obj);
        }
        
        this.MovementHandler = function(e)
        {
            MManager.HandlerEx(e, MManager.hTypeHover);
        }

        this.ClickHandler = function(e)
        {
            if(MManager.HandlerEx(e, MManager.hTypeClick) == false)
                (e || event).returnValue = false;
        }
        
        this.testClassName = function(itemClassName, ruleClassName)
        {
            if(itemClassName && ruleClassName)
            {
                var classes = itemClassName.split(' ');
                for(var i = 0; i < classes.length; i++)
                {
                    if(classes[i] == ruleClassName)
                        return true;
                }
            }
            
            return false;
        }

        this.HandlerEx = function (e, iEventType)
        {
            var bSuppressCancelEvent = undefined;

            var p = (e && e.target ? e.target : event.srcElement);
            var source = p;
            //if(this.handlers.length != 0)
            //{
            var ev = e || event;

            while (p)
            {
                for (var i = 0; i < this.handlers.length; i++)
                {
                    var rule = this.handlers[i];
                    if (rule.handlerType != iEventType)
                        continue;

                    var h;
                    if (iEventType == this.hTypeHover && (h = this.getHovered(p)) && h.state != -1) // this is correct. must be '='
                    {
                        h.state = 1;
                    }
                    else
                    {
                        if (rule.className && this.testClassName(p.className, rule.className)
                                || p == rule.control
                                || p.controlID && p.id && (p.id == rule.controlID || rule.notStrong && p.id.indexOf(rule.controlID) != -1))
                        {
                            if (iEventType == this.hTypeHover)
                            {
                                //var z = 0;
                                //if(z == 1)
                                //  z = z.z.z;
                                var obj = new Object();
                                obj.obj = p;
                                obj.state = -1;
                                obj.rule = rule;
                                if (p.className)
                                    obj.className = p.className;
                                if (!rule.hoverClassName && p.getAttribute('hvclass'))
                                    obj.hoverClassName = p.getAttribute('hvclass');

                                this.hovered.push(obj);
                            }
                            else if (rule.handlerClick && bSuppressCancelEvent != false)
                            {
                                if (bSuppressCancelEvent != false)
                                    bSuppressCancelEvent = rule.handlerClick(ev, source, p);
                            }
                        }
                    }
                }

                if (bSuppressCancelEvent != false && iEventType == this.hTypeClick && p.className && (p.className.indexOf('gh-') == 0 || p.className.indexOf(' gh-') != -1))
                {
                    var sCommandPrefix = 'gh-command-';
                    var sPageCommandPrefix = 'gh-page-';
                    if (mbi.extensions.HasCssClass(p, 'gh-tab'))
                    {
                        this.processTabClick(ev, source, p);
                        bSuppressCancelEvent = false;
                    }
                    else if (p.className.indexOf(sCommandPrefix) != -1)
                    {
                        var cls = p.className.split(' ');
                        for (var z = 0; z < cls.length; z++)
                        {
                            var cl = cls[z];
                            var _n = cl.indexOf(sCommandPrefix);
                            if (_n == 0)
                            {
                                var sCommandName = cl.substr(sCommandPrefix.length, cl.length - sCommandPrefix.length);
                                var _fn = mbi.cmanager.commands[sCommandName];
                                if (_fn)
                                {
                                    bSuppressCancelEvent = _fn(p.cobject || p);

                                }
                                else alert('Cmanager command for \'' + sCommandName + '\' event is not implemented!');
                                break;
                            }
                        }
                    }
                    else if (p.className.indexOf(sPageCommandPrefix) != -1)
                    {
                        var cls = p.className.split(' ');
                        for (var z = 0; z < cls.length; z++)
                        {
                            var cl = cls[z];
                            var _n = cl.indexOf(sPageCommandPrefix);
                            if (_n == 0)
                            {
                                bSuppressCancelEvent = mbi.page[cl.substr(sPageCommandPrefix.length, cl.length - sPageCommandPrefix.length)](p);
                                break;
                            }
                        }
                    }
                }

                if (iEventType == this.hTypeHover)
                {
                    for (var i = 0; i < this.hovered.length; i++)
                    {
                        if (this.hovered[i].obj == p && this.hovered[i].state != -1)
                        {
                            this.hovered[i].state = 1;
                        }
                    }
                }

                p = p.parentNode;
            }
            //}

            if (this.hTypeClick == iEventType)
                return bSuppressCancelEvent;

            var i = 0; // to process outs first
            this.hovered.sort(function (_s1, _s2) { return _s1.state == 0 ? (_s2.state == 0 ? 0 : -1) : 0 });
            while (i < this.hovered.length)
            {
                var item = this.hovered[i];
                if (item.state == 0)
                {
                    var bCancel = false;
                    //if (item.rule.handlerOut)
                    //{
                        if (item.rule.inTimer)
                        {
                            window.clearInterval(item.rule.inTimer);
                            item.rule.inTimer = null;
                        }
                        else if (item.rule.params.outDelay)
                        {
                            if (item.rule.outTimer)
                            {
                                // nothing to do: waiting
                            }
                            else
                            {
                                var iOutTime = item.rule.params.inDelay || item.rule.params.outDelay;
                                item.rule.outTimer = (function (item) { window.setTimeout(function () { mbi.handlers.outHoverDelay(item); }, item.rule.params.outDelay > iOutTime ? iOutTime : item.rule.params.outDelay); })(item);
                            }
                        }
                        else if (item.rule.handlerOut) bCancel = item.rule.handlerOut(item.obj, source);


                    //}
                    item.rule.lastHovered = null;

                    if (!bCancel)
                    {
                        if (item.className && item.rule.hoverClassName)
                        {
                            item.obj.className = Extensions.ReplaceCssClass(item.obj.className, item.rule.hoverClassName, item.rule.className);
                        }

                        this.hovered.splice(i, 1);
                        continue;
                    }
                    else item.state = 0;
                }
                else
                {
                    if (item.state == -1)
                    {
                        //if (item.rule.handlerIn)
                        //{
                            if (item.rule.outTimer)
                            {
                                if (item.rule.hoveredObject == item.obj)
                                {
                                    window.clearInterval(item.rule.outTimer);
                                    item.rule.outTimer = null;
                                }
                            }
                            else
                            {
                                if (item.rule.params.inDelay || item.rule.params.outDelay)
                                {
                                    var bInDelay = false;
                                    if (item.rule.fnInDelay)
                                    {
                                        bInDelay = item.rule.fnInDelay(item.obj, source);
                                        if (bInDelay)
                                        {
                                            bCancel = item.rule.handlerIn(item.obj, source);
                                        }
                                    }
                                    if (!bInDelay)
                                    {
                                        //if(item.rule.hoveredObject)
                                        //{
                                        //item.rule.lastHovered = item.obj;
                                        if (item.rule.inTimer)
                                        {
                                            window.clearTimeout(item.rule.inTimer);
                                            item.rule.inTimer = null;
                                        }
                                        item.rule.inTimer = (function (item, source) { window.setTimeout(function () { mbi.handlers.inHoverDelay(item, source); }, item.rule.params.inDelay || item.rule.params.outDelay); })(item, source);
                                        //}
                                    }
                                }
                                else if(item.rule.handlerIn) bCancel = item.rule.handlerIn(item.obj, source);

                                if (!item.rule.hoveredObject)
                                    item.rule.hoveredObject = item.obj;
                            //}
                            item.rule.lastHovered = item.obj;
                        }

                        if (!bCancel)
                        {//alert(item.obj.className +  ' ' + item.rule.className +  ' ' + item.rule.hoverClassName);
                            if (item.rule.hoverClassName)
                                item.obj.className = Extensions.ReplaceCssClass(item.obj.className, item.rule.className, item.rule.hoverClassName);
                        }
                    }

                    item.state = 0;
                }
                i++;
            }

            for (var i = 0; i < this.movers.length; i++)
            {
                var it = this.movers[i];
                this.processMover(it);
            }

            return bSuppressCancelEvent;
        }

        this.outHoverDelay = function (item)
        {
            if (item.rule.handlerOut) item.rule.handlerOut(item.obj, item.obj);

            item.rule.hoveredObject = null;
            if (item.rule.lastHovered && item.rule.handlerIn)
            {
                item.rule.hoveredObject = item.obj;
                item.rule.handlerIn(item.obj, item.obj);
            }
        }
        this.inHoverDelay = function (item, source)
        {
            item.rule.hoveredObject = item.obj;
            if (item.rule.handlerIn) item.rule.handlerIn(item.obj, source);
        }

        this.getHovered = function(obj)
        {
            for(var i = 0; i < this.hovered.length; i++)
            {
                if(this.hovered[i].obj == obj)
                    return this.hovered[i];
            }
            return null;
        }

        this.processTabClick = function (e, source, sender)
        {
            e.returnValue = false;

            if (transition) return;
            transition = transition;

            var p = sender.parentNode;

            var tabs = $(sender.parentNode).find('.gh-tab');

            //var tabsContainer = null;
            //if(p.getAttribute('containerid'))
            //    tabsContainer = $get(p.getAttribute('containerid'));

            var tabsDivs = $(sender.parentNode.parentNode).find('.g-tab-content');

            var tabHide = null;
            var tabShow = null;

            for (var i = 0; i < tabs.length; i++)
            {
                var tab = tabs[i];
                if (tab == sender)
                {
                    if (Extensions.HasCssClass(tab, 'act'))
                        return;
                    else
                    {
                        Extensions.AddCssClass(tab, 'act');
                        //$(sender.parentNode).find(".expanded").toggleClass("act");

                        var classes = sender.className.split(' ');
                        var sTabContClass = null;
                        for (var z = 0; z < classes.length; z++)
                        {
                            if (classes[z].indexOf('gh-tab-') == 0)
                            {
                                sTabContClass = classes[z].replace('gh-tab-', '');
                                break;
                            }
                        }
                        if (sTabContClass)
                        {
                            for (var j = 0; j < tabsDivs.length; j++)
                            {
                                var tb = tabsDivs[j];
                                if (Extensions.HasCssClass(tb, 'act'))
                                {
                                    if (Extensions.HasCssClass(tb, 'g-tab-content-' + sTabContClass))
                                        break;
                                    else
                                        tabHide = tb;
                                }
                                else if (Extensions.HasCssClass(tb, 'g-tab-content-' + sTabContClass))
                                    tabShow = tb;
                            }
                        }
                    }
                }
                else
                {
                    Extensions.RemoveCssClass(tab, 'act');
                }
            }

            if (tabHide)
            {
                if (ie)
                    tabHide.style.width = tabHide.offsetWidth + 'px';

                actM.addAction(new action(tabHide, 100, 0, 'opacity', 150, 0, function (obj)
                {
                    if (ie)
                        obj.style.width = '';

                    obj.style.display = 'none';
                    tabShow.style.display = '';

                    Extensions.RemoveCssClass(tabHide, 'act');
                    Extensions.AddCssClass(tabShow, 'act');

                    if (ie)
                        tabShow.style.width = tabShow.offsetWidth + 'px';

                    actM.addAction(new action(tabShow, 0, 100, 'opacity', 150, 0, function (obj1) { transition = false; if (ie) obj1.style.width = ''; }));
                }));
            }
            else if (tabShow)
            {
                tabShow.style.display = '';
                Extensions.AddCssClass(tabShow, 'act');
                actM.addAction(new action(tabShow, 0, 100, 'opacity', 150, 0, function (obj) { transition = false; }));
            }
        }

        this.movers = new Array();
        
        this.attachMover = function(objToMove, xPos, yPos, handler, objToMoveInContainer)
        {
            var obj = new Object();
            obj.element = objToMove;
            obj.x = xPos || 0;
            obj.y = yPos || 0;
            obj.handler = handler;
            obj.container = objToMoveInContainer; // not implemented
            
            this.movers.push(obj);
            this.processMover(obj);
            
            return obj;
        }
        
        this.detachMover = function(obj, objToMoveIsMover) // false - element, true - mover
        {
            for(var i = this.movers.length - 1; i >=0; i--)
            {
                var it = this.movers[i];
                if(objToMoveIsMover && obj == it || !objToMoveIsMover && obj == it.element)
                    this.movers.splice(i, 1);
            }
        }
        
        this.processMover = function(moverObj)
        {
            moverObj.element.style.top = (yMousePos + moverObj.y) + 'px';
            moverObj.element.style.left = (xMousePos + moverObj.x) + 'px';
            if(moverObj.handler)
                moverObj.handler(moverObj);
        }

        this.tooltips = new Array();
        this.tooltipShow = function (content, args)
        {
            args = args || new Object();

            var t = this.tooltips[0];
            if (this.tooltips.length != 1)
            {
                t = new Object();
                t.params = args;

                this.tooltips.push(t);

                var el = document.createElement('div');
                t.element = el;
                el.className = args.css || '';
                el.style.position = 'absolute';
                el.style.zIndex = args.css ? '' : '999999';
                el.style.backgroundColor = args.css ? '' : 'black';
                el.style.color = args.css ? '' : 'white';
                
                document.body.appendChild(el);
            }

            if(typeof(content) == 'string')
                t.element.innerHTML =  content;
            else
            {
                t.element.innerHTML = '';
                t.element.appendChild(content);
            }

            t.element.style.display = 'block';
            this.attachMover(t.element, 15, 15);
        }
        
        this.setTooltipContent = function(content)
        {
            if(this.tooltip)
            {
                this.tooltip.contentContainer.innerHTML = content || '';
            }
        }

        this.tooltipHide = function (tooltip)
        {
            var t = tooltip || this.tooltips[0];
            t.element.style.display = 'none';
            this.detachMover(t.element);
        }
    }
    
    MManager = new MoveHoverManager();
//    AddBrowserHandler(document, 'mousemove', function(e){var p = (e && e.target ? e.target : event.srcElement);window.status = ''; while(p) {window.status = p.tagName + ' | ' + window.status; p = p.parentNode;}});
    AddBrowserHandler(document, 'mousemove', MManager.MovementHandler);
    AddBrowserHandler(document, 'click', MManager.ClickHandler);

    mbi.handlers = MManager;
//    AddBrowserHandler(window, 'load', performance0);
    
    var pobj = null;
    var ii = 0;
    var dFrom = null;
    var bIn = false;
    function performance0()
    {
        if(bIn)
            return;
            
        bIn = true;
        performance();
    }
    function performance()
    {
        if(!pobj)
        {
            pobj = document.createElement('div');
            pobj.style.width = '200px';
            pobj.style.height = '200px';
            pobj.style.backgroundColor = 'White';
            pobj.style.backgroundImage = 'url(app_themes/silver/images/loading2.gif)';
            pobj.style.position = 'absolute';
            pobj.style.top = '0';
            pobj.style.left = '0';
            pobj.style.border = '1px solid red';
            
            dFrom = new Date();
            
            document.body.insertBefore(pobj, null);
        }
        
        if(ie)
            pobj.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + ii + ')';
        else
        {
            var op = ii / 100;
            pobj.style.MozOpacity = op;
            pobj.style.opacity = op;
            pobj.style.KhtmlOpacity = op;
        }
        
        if(ii++ < 100)
        {
            window.setTimeout('performance();', 0);
        }
        else
        {
            var t = new Date() - dFrom;
            //window.status = t / 1000;
            alert('' + (t / 1000));
        }
    }
    
/**********************************************/

//AddBrowserHandler(document, 'mousemove', tmp);
//AddBrowserHandler(window, 'scroll', tmp2);
//AddBrowserHandler(window, 'resize', tmp2);

var iScrollCurrentSpeed = 0;
var bCalledManually = false;
var dontScroll = false;
function tmp2()
{
    if(!bCalledManually)
        iScrollCurrentSpeed = 0;
    bCalledManually = false;
}
function tmp(e)
{
    var s = getWindowSize()[1];//window.status = document.documentElement.scrollTop;
    var sp = (yMousePos - f_scrollTop()) / s * 100 - 50;
    
    if(Math.abs(sp) > 10) // not in center area
    {
        var iSign = sp > 0 ? 1 : -1;
        iScrollCurrentSpeed = iSign * Math.round((Math.abs(sp) - 10) * 2);
        //window.status = iScrollCurrentSpeed;
    }
    else iScrollCurrentSpeed = 0;
}
function updateScroll()
{
    if(iScrollCurrentSpeed != 0 && !dontScroll)
    {
        bCalledManually = true;
        window.scrollBy(0, iScrollCurrentSpeed);
    }
    //document.body.scrollTop = '' + document.body.scrollTop + iScrollCurrentSpeed;
}
window.setInterval(updateScroll, 50);


function f_clientWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function f_clientHeight() {
	return f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}
function f_scrollLeft() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

/// Image User Control
// popupImageManager.ClientID, imgPhoto.ClientID, imgChangePhoto.ClientID, hdnPhotoUID.ClientID, hfImgParam.ClientID, sldSize.ClientID

    function BeforeSaveImage(popupImageManagerId, imgPhotoId, imgChangePhotoId, hdnPhotoUIDId, hfImgParamId, sldSizeId)
    {
        var hdnValue = $get(hdnPhotoUIDId).value;
        
        if(hdnValue == '-1') // image has removed
        {
            CloseImageManagerRemoved(popupImageManagerId, imgPhotoId);
        }
        else if(hdnValue != '') // image was modified
        {
            // Setting the image parameters to a hiden fields. Also, setting the preview image
            var imgChange = $get(imgChangePhotoId);
            var imgPreviewPhoto = $get(imgPhotoId);
            var top = imgChange.style.top ? parseInt(imgChange.style.top.replace('px','')) : 0;  
            var left = imgChange.style.left ? parseInt(imgChange.style.left.replace('px','')) : 0;  
            $get(hfImgParamId).value = left + '|' + top + '|' + ($find(sldSizeId).get_value() / 100) + '|' + imgChange.style.width.replace('px','') + '|' + imgChange.style.height.replace('px','');
            
            imgPreviewPhoto.style.left = imgChange.style.left;
            imgPreviewPhoto.style.top = imgChange.style.top;
            imgPreviewPhoto.style.width = imgChange.style.width;
            imgPreviewPhoto.style.height = imgChange.style.height;
            
            imgPreviewPhoto.src = imgChange.src; // BasePath + 'GetImage.ashx?type=tmp&id=' + $get(hdnPhotoUIDId).value + '&rnd=' + Math.random();
            
            var popupImageManager = $get(popupImageManagerId);
            popupImageManager.hide();
            var evt = popupImageManager.getAttribute('onclientimagechanged');
            if(evt) 
                eval(evt + "('"+popupImageManagerId+"','"+hdnValue+"');");
        }
        else // operation canceled
        {
            CloseImageManagerCancel(popupImageManagerId);
        }
         
    } 
    
    function RemoveImage(imgChangeId, hdnPhotoUIDId, sldSizeId)
    { 
        var imgChange = $get(imgChangeId);
        var slider = $find(sldSizeId);
        $get(hdnPhotoUIDId).value = '-1';  

        imgChange.style.display = 'none';
        slider.set_value(100); 
        slider.set_enabled(false);  
        slider.redraw();  
        imgChange.style.top = '0px'; 
        imgChange.style.left = '0px'; 
        imgChange.style.width = '150px';  
        imgChange.style.height = '150px';
        
        imgChange.src = BasePath + 'GetImage.ashx?id=0';
        imgChange.style.display = '';
   }
   
    function findPos(obj)
    {
	    var curleft = curtop = 0;
	    if (obj.offsetParent)
	    {
		    curleft = obj.offsetLeft
		    curtop = obj.offsetTop
		    while (obj = obj.offsetParent)
		    {
			    curleft += obj.offsetLeft
			    curtop += obj.offsetTop
            }
	    }
	    
	    return [curleft,curtop];
    } 
   
    function gErrorHandler(message, messageEx)
    {
        
    }


//// Tab Animation events handlers

    var tab_selecting = false;
    var tab_prevent_event = false;
         
 	function OnClientTabSelecting(sender, eventArgs)
	{
        if(!tab_selecting && !tab_prevent_event)
	    {
	        eventArgs.set_cancel(true);		
	        tab_selecting = true;
	        tab_prevent_event = true;
	        
	        var tabDiv = sender.get_selectedTab().get_pageView().get_element();
	        tabDiv.style.width = tabDiv.offsetWidth.toString() + 'px';
	        //tabDiv.style.height = tabDiv.offsetHeight.toString() + 'px';
	        
	        actM.addAction( new action(tabDiv, 100, 0, 'opacity', 130, 0, 
	        function(obj) { tab_prevent_event = false; eventArgs.get_tab().select(); tab_prevent_event = true; }));	 
	    }
	    else if (!tab_prevent_event) eventArgs.set_cancel(false); else eventArgs.set_cancel(true);
	}
    
    function OnClientTabSelected(sender, eventArgs)
    {
        var tabPage = eventArgs.get_tab().get_pageView();
        actM.addAction(new action(tabPage.get_element(), 0, 100, 'opacity', 130, 0, 
        function(obj) { tab_selecting = false; tab_prevent_event = false; }, 0));
    }
    
    
    /// UCSongDetails

    function setCheckedForUpdate(sender)
    {
       var ctrl = sender.parentNode.getElementsByTagName('input');
       if(ctrl && ctrl[0] && ctrl[0].type == 'checkbox')
            ctrl[0].checked = true;
    }


//// Custom Validation Manager

    function ValidationManager()
    {
        this.groups = new Array();
        this.validators = new Array();
        
        this.validateGroup = function(sGroupName)
        {
            var bValid = true;
            var oGroup = this.getGroup(sGroupName);
            
            if(oGroup)
            {
                for (var j = 0; j < oGroup.validators.length; j++)
                {
                    var v = oGroup.validators[j];
                    if(!v.validate())
                        bValid = false;
                }
            }
            else bValid = true;
            
            return bValid;
        }
        
        this.initializeValidator = function(validator)
        {
            var oGroup = this.getGroup(validator.groupName);
            if(oGroup == null)
            {
                var o = new Object();
                o.groupName = validator.groupName;
                o.validators = new Array();
                o.validators.push(validator);
                this.groups.push(o);
            }
            else
            {
                var v = null;
                for (var i = 0; i < oGroup.validators.length; i++)
                {
                    var it = oGroup.validators[i];
                    if(it.uniqueName == validator.uniqueName)
                    {
                        v = it;
                        break;
                    }
                }
                if(v == null)
                {
                    oGroup.validators.push(validator);

                    v = this.getValidator(validator.uniqueName);                    
                    if(v == null)
                        this.validators.push(validator);
                }
            }
        }
        
        this.hideValidAndActive = function(sGroupName, sValidatorUniqueName)
        {           
            var oGroup = this.getGroup(sGroupName);
            if(oGroup != null)
            {
                for (var i = 0; i < oGroup.validators.length; i++)
                {
                    var it = oGroup.validators[i];
                    if(it.uniqueName == sValidatorUniqueName)
                    {
                        if(!it.activated)
                        it.validate();
                    }
                }
            }
        }
        this.resetValidators = function(sGroupName)
        {           
            var oGroup = this.getGroup(sGroupName);
            if(oGroup != null)
            {
                for (var i = 0; i < oGroup.validators.length; i++)
                {
                    var it = oGroup.validators[i];
                    it.setActivity(false);
                }
            }
        }
        
        this.getGroup = function(sGroupName)
        {
            for (var i = 0; i < this.groups.length; i++)
            {
                var it = this.groups[i];
                if(it.groupName == sGroupName)
                {
                    return it;
                }
            }
            return null;
        }
        this.getValidator = function(sValidatorUniqueName)
        {
            for (var i = 0; i < this.validators.length; i++)
            {
                var it = this.validators[i];
                if(it.uniqueName == sValidatorUniqueName)
                {
                    return it;
                }
            }
            return null;
        }
    }
    function ValidationItem(sControlName, sControlToCompareName, iType, sValidationGroup, bMustHaveValue, iPosX, iPosY, customHandler, sErrorMessage, sValidatorUniqueName, sClassName, sRegex, iMinLength)
    {
        this.controlName = sControlName;
        this.control = $get(sControlName);
        this.controlToCompareName = sControlToCompareName;
        this.controlToCompare;
        if(this.controlToCompareName)
            this.controlToCompare = $get(sControlToCompareName);
        this.type = iType;
        this.groupName = sValidationGroup;
        this.mustHaveValue = bMustHaveValue;
        this.posX = iPosX;
        this.posY = iPosY;
        this.handler = customHandler;
        this.errorMessage = sErrorMessage;
        this.uniqueName = sValidatorUniqueName;
        this.className = sClassName || null;
        this.regex = sRegex;
        this.minimumLength = iMinLength;
        
        this.enabled = true;
        this.activated = false;
        
        this.instanceControl = null;
        
        this.validate = function()
        {
            var v = this.isValid();
            
            this.setActivity(!v);
            
            return v;
        }
        
        this.isValid = function()
        {                     
            var bIsValid = true;
            if(this.handler)
                bIsValid = this.handler(this.control);
            else
            {
                if(this.control == null)
                return bIsValid;
                
                var sTag = (this.control.tagName || '').toLowerCase();
                var sType = (this.control.type || '').toLowerCase();
                if(sTag == 'input' && (sType == 'text' || sType == 'password') || sTag == 'textarea') // textboxes
                {
                    if(this.mustHaveValue && this.control.value == '')
                    {
                        bIsValid = false;
                    }
                    if(bIsValid && this.regex)
                    {
                        if(!this.control.value.match(new RegExp(this.regex, "g")))
                            bIsValid = false;
                    } 
                    if(bIsValid && (this.type == 1 || this.type == 2))
                    {
                        if(isNaN(this.type == 1 ? parseInt(this.control.value) : parseFloat(this.control.value)))
                            bIsValid = false;
                    }
                    if(bIsValid && this.type == 3)
                    {
                        if(!this.control.value.match(new RegExp(EmailRegexValidationString, "i")))
                            bIsValid = false;
                    }
                    if(bIsValid && this.controlToCompare)
                    {
                        if(this.control.value != this.controlToCompare.value)
                            bIsValid = false;
                    }
                    if(bIsValid && this.minimumLength > 0)
                    {
                        if(this.control.value.length < this.minimumLength)
                            bIsValid = false;
                    }
                }
                else if(sTag == 'input' && (sType == 'checkbox' || sType == 'radio'))
                {
                    if(this.mustHaveValue && !this.control.checked)
                        bIsValid = false;
                }
                else if(sTag == 'span' || sTag == 'div' || sTag == 'table')
                {
                    if(this.mustHaveValue)
                    {
                        var bIsChecked = false;
                        var items = this.control.getElementsByTagName('input');
                        for(var i = 0; i < items.length; i++)
                        {
                            var it = items[i];
                            if(it.checked)
                            {
                                bIsChecked = true;
                                break;
                            }
                        }
                        
                        if(!bIsChecked)
                            bIsValid = false;
                    }
                }
                else if(sTag == 'select')
                {
                    if(this.mustHaveValue && (this.control.options.length == 0 || this.control.options[this.control.selectedIndex].value == '' || this.control.options[this.control.selectedIndex].value <= 0))
                    {
                        bIsValid = false;
                    }
                    if(bIsValid && this.controlToCompare)
                    {
                        if(this.control.value != this.controlToCompare.value)
                            bIsValid = false;
                    }
                }
            }
            
            return bIsValid;
        }        
        
        this.setActivity = function(bActive)
        {
            if(!this.instanceControl)
                this.initialize();
                
            if(!this.instanceControl)
                return;
            
            if(bActive)
            {
                this.instanceControl.style.display = '';
                //if(!this.activated)
                    // actM. ...
            }
            else
            {
                this.instanceControl.style.display = 'none';
                if(this.activated)
                    {}// actM. ...
            }
            
            this.activated = bActive;
            // hide/show
        }
        
        this.initialize = function()
        {
            if(this.control == null)
            return;
            
            var o = document.createElement('div');
            this.instanceControl = o;
            o.style.width = '0';
            o.style.height = '0';
            o.style.overflow = 'visible';
            o.style.position = 'relative';
            o.style.clear = 'both';
            o.style.display = 'none';
            var y = this.control.offsetHeight;
            y += this.posY;
            y = this.posY;
            o.innerHTML = '<span style="font-size:12px;padding:1px;position:relative;white-space:nowrap;background:darkred;color:white;top:' + y + 'px;' + '" class="' + (this.className ? 'Validator_Default' : this.className) + '"><span class="core">' + this.errorMessage + '</span></span>'
            
            this.control.parentNode.insertBefore(o, null);//this.control);
        }
    }
    
    var valM = new ValidationManager();


/* scrolling */
/*function include(file)
{
    var script  = document.createElement('script');
    script.src  = file;
    script.type = 'text/javascript';
    script.defer = true;
    document.getElementsByTagName('head').item(0).appendChild(script);
}
include('js/tmp_scrolling.js');
*/

function FileManagerCore()
{
    this.container = null;
    this.urlContainer = null;
    
    this.extensionsContainer = null;
    this.frameContainer = null;
    
    this.InitializeManager = function(dlgClientID, txtUrlClientID, frmContClientID, sExtensionsClientID, sUploadUrl)
    {
        this.container = $get(dlgClientID);
        this.urlContainer = $get(txtUrlClientID);
        this.frameContainer = $get(frmContClientID);
        this.extensionsContainer = $get(sExtensionsClientID);
        this.url = sUploadUrl;
    };
    
    this.ObtainFile = function(oExtensions, callBack, isImage)
    {
        this.callBack = null;
        
        if(this.container == null)
        {
            alert('FileManager is not initialized.');
            return;
        }
        else
        {
            this.isImage = isImage;
            this.callBack = callBack;
            this.urlContainer.value = '';
            this.container.show();
            this.extensionsContainer.innerHTML = (oExtensions.length > 0 ? "*." : "") + oExtensions.join(', *.');
            this.frameContainer.innerHTML = "<iframe id='pnlUniversalUpload' name='pnlUniversalUpload' style='width: 300px; height: 30px; border: 0 white;' scrolling='no' " +
                    "src='" + this.url + "?auto=FileManager.ImageUploaded&senderID=&ext=" + oExtensions.join('|') + "&progressid=&param1=&param2=&param3=&param4=" + (isImage ? '&isimage=1' : '') + "' frameborder='0'></iframe>"
        }
    }
    
    this.ImageUploaded = function(params)
    {
        if(this.callBack)
        {
            this.callBack(params);
        }
        this.container.hide();
    }
    
    this.RetrieveImageFromURL = function()
    {
        if(this.urlContainer.value == '')
        {
            alert('Value can not be empty');
            return;
        }
        
        PageMethods.UploadRemoteImage(this.urlContainer.value, this.isImage == true, FileManager_UploadRemoteImageOk, function(){});
    }
    
    this.UploadRemoteImageOk = function(pmInfo)
    {
        var res = pmInfo.Result;
        if(res[1])
        {
            alert(res[1]);
        }
        else if(this.callBack)
        {
            var obj = new Object();
            obj.fileNewName = res[0];
            obj.fileOldName = '';
            obj.SongTitle = '';
            obj.param1 = null;
            obj.param2 = null;
            obj.param3 = null;
            obj.param4 = null;

            obj.imageInfo = res[2];
            
            //obj.senderID
            
            this.callBack(obj);
            
            this.container.hide();
        }
    }
}
function FileManager_UploadRemoteImageOk(res)
{
    FileManager.UploadRemoteImageOk(res);
}
var FileManager = new FileManagerCore();

function FilesUploaderManager(oContainer, oItemsContainer, sVarName, oStartUploadBtn, oCancelBtn, onSongUploadedCallback) {
    
    this.onSongUploaded = onSongUploadedCallback;
    this.itemsContainer = oItemsContainer;
    this.button = oStartUploadBtn;
    
    if(!oContainer.id)
        oContainer.id = GGenerateGuid();

    this.id = oContainer.id + '_fl';

    this.ccontainer = CManager.ParseCControl(oItemsContainer);
    
    if (swfobject.hasFlashPlayerVersion("9")) {
        var params =
                {
                    'allowfullscreen': 'true',
                    'allowScriptAccess': 'always',
                    'wmode': 'transparent',
                    'javascriptid': this.id,
                    'flashvars': 'uploaderControlName=' + (sVarName || ''),
                    'enaglejs': 'true'
                };

        var atts = { id: this.id, name: this.id };
        swfobject.embedSWF(GAppRoot + "swf/fileuploader.swf?zz14",
                oContainer.id, "148", "24", "9.0.0", "expressInstall.swf", null, params, atts);
    }
    else {oContainer.innerHTML = '<a href="http://www.adobe.com/go/getflashplayer"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a>';}

/*
    var attributes = {name:this.id, id:this.id};
    
    var s1 = new SWFObject("fileuploader.swf", this.id, "80","40","9","transparent", null, null, attributes);
    s1.addParam("allowfullscreen","true");
    s1.addParam("allowscriptaccess","always");
    s1.addParam("flashvars","uploaderControlName=" + (sVarName || ''));
    s1.addParam('wmode','transparent');
    s1.addParam('javascriptid',this.id);
    s1.addParam('enablejs', 'true');
    s1.write(oContainer.id);*/
    
    this.onLoaded = function()
    {
        
    }
    
    this.filesClear = function()
    {
        this.itemsContainer.innerHTML = '';
    }
    this.addFile = function(i, sName, iSize)
    {
        var el = this.ccontainer.templates.fileitem.container.cloneNode(true);
        el.innerHTML = el.innerHTML.replace('{0}', i).replace('{1}', sName).replace('{2}', GFormatFileSize(iSize));
        var control = CManager.InsertCControl(this.ccontainer, el, null, '@items');
        control.show();
        
        this.updateState();
    }
    /*this.uploadingStarted = function(n)
    {
        var items = Extensions.GetChildNodes(this.itemsContainer, 'div');
        var sp = items[i].getElementsByTagName('span')[0];
        sp.innerHTML = 'processing';
    }*/
    this.uploadProgress = function(i, iBytesLoaded, iBytesTotal)
    {
        var items = this.ccontainer.controls.items;
        var it = items[i];
        
        var per = iBytesLoaded / iBytesTotal;
        it.controls.status.container.innerHTML = Math.round(per * 100) + '%';
        
        var p = it.controls.progress;
        var p0 = p.controls.value.container;
        
        p0.style.width = Math.round(p.container.clientWidth * per) + 'px';
    }
    this.uploadComplete = function(i, sData)
    {
        var items = this.ccontainer.controls.items;
        var it = items[i];
        
        it.tag = sData;
        it.controls.progress.controls.value.hide();
        it.controls.status.container.innerHTML = 'done';
        
        if(this.onSongUploaded)
            this.onSongUploaded(it, i == items.length - 1);
    }
    
    this.startUploading = function()
    {
        var items = this.ccontainer.controls.items;
        if(items)
        {
            for (var i = 0; i < items.length; i++)
            {
                var it = items[i];
                it.controls.remove.hide();
                it.controls.progress.show();
                it.controls.status.show();
                it.controls.status.container.innerHTML = 'waiting';
            }
        }

        this.button.disabled = true;
        
        this.getInstance().setEnabled(false);
        this.getInstance().startUploading();
    }
    this.removeFileInstance = function(cobj)
    {
        var n = -1;
        for (var i = 0; i < cobj.parentCollection.length; i++)
        {
            var it = cobj.parentCollection[i];
            if(it == cobj)
            {
                n = i;
                break;
            }
        }
        CManager.RemoveControl(cobj);

        this.getInstance().deleteFile(n);
        this.updateState();
    }
    this.updateState = function()
    {
        var gr = this.ccontainer.controls.items;
        var iCount = gr ? gr.length : 0;
        if(iCount == 0)
        {
            this.ccontainer.controls.empty.show();
            if (this.button) this.button.title = 'You should select files to upload first';
        }
        else
        {
            this.ccontainer.controls.empty.hide();
            if (this.button) this.button.title = '';
        }
        if (this.button) this.button.disabled = iCount == 0;
        
        var items = this.ccontainer.controls.items;
        if(items)
        {
            for (var i = 0; i < items.length; i++)
            {
                var it = items[i];
                it.controls.number.container.innerHTML = i + 1;
                if(i % 2 == 0)
                {
                    if(it.container.className == 'alt')
                        it.container.className = '';
                    else if(it.container.className.indexOf(' alt') > -1)
                        it.container.className = it.container.className.replace(' alt', '');
                }
                else
                {
                    if(it.container.className.indexOf(' alt') == -1 && it.container.className != 'alt')
                        it.container.className = it.container.className + ' alt';
                }
            }
        }
    }
    
    this.getInstance = function()
    {
        if(navigator.appName.indexOf("Microsoft") != -1)
        {
            return document.getElementsByName(this.id)[0]; //return window[gid]; this was in a sample, but it doesn't work. the next like works fine
        }
        else return document[this.id];
    }
    
}

function ExtensionsManager()
{

    /* dropdown managing */
    this.dropdownManagementInitialized = false;
    this.dropdownObjects = new Array();
    this.activeDropdownObjects = new Array();
    
    this.InitializeDropdownsManagement = function()
    {
        if(this.dropdownManagementInitialized)
            return;
        
        MManager.addClickHandler(null, function(e, source, sender){return Extensions.DropdownButtonOnClick(e, source, sender);}, 'GHDropdownButton');
    
        AddBrowserHandler(document, "mousedown", Extensions_DropdownManagementDownHandler);
        AddBrowserHandler(document, "click", Extensions_DropdownManagementHandler);
        AddBrowserHandler(window, 'resize', Extensions_DropdownManagementScrollHandler);
        AddBrowserHandler(window, 'scroll', Extensions_DropdownManagementScrollHandler);
        this.dropdownManagementInitialized = true;
    }

    this.DropdownButtonOnClick = function(e, source, sender)
    {
        var el = sender.getAttribute('itemscontainer') ? $get(sender.getAttribute('itemscontainer')) : null;
        var p = sender.getAttribute('parentcontainer') ? $get(sender.getAttribute('parentcontainer')) : sender;
        //if(el.style.display == '')
        //    Extensions.CancelDropdownProcessing(el);
        //else
        //{
        
        if(!sender.cobject.isenabled())
            return;
            
            var params = new Object();
            params.element = el;
            params.parent = p;
            params.clicker = sender;
            params.scroller = null;
            params.callback = null;
            params.leftAligned = sender.getAttribute('ddlRight') != '1';
            params.hideOnInnerClick = sender.getAttribute('static') != '1';
            params.onOpening = sender.getAttribute('onDdlOpening') ? eval(sender.getAttribute('onDdlOpening')) : null;
            this.ProcessDropdown(params);
        //}
        return false;
    }
    
    this.InitializeDropdown = function(sClientIDOrObj, iColumnsCount)
    {
        this.InitializeDropdownsManagement();
        var el = sClientIDOrObj;
        if(typeof el == 'string')
            el = $get(sClientIDOrObj);
        
        el.getValue = this.GetDropdownValue;
        el.setValue = this.SetDropdownValue;
        el.setValueEx = this.SetDropdownValueEx;
        
        var obj = this.FindDropdown(el);
        if(!obj)
        {
            obj = new Object();
            obj.parent = el;
            obj.columns = iColumnsCount || 1;
            this.dropdownObjects.push(obj);
        }
    }
    this.GetDropdownValue = function()
    {
        return this.getAttribute('sel');
    }
    this.SetDropdownValue = function(value)
    {
        Extensions.SetDropdownValueEx(value, true, this);
    }
    this.SetDropdownValueEx = function(value, suppressOnChangeEvent, el)
    {
        var dr = null;
        for (var i = 0; i < Extensions.activeDropdownObjects.length; i++)
        {
            var it = Extensions.activeDropdownObjects[i];
            if(it.clicker == this || it.parent == this)
            {
                dr = it;
                break;
            }
        }
        
        if(!dr && el)
            dr = Extensions.FindDropdown(el);
        
        if(dr && (dr.celement || dr.element))
        {
            var items = (dr.celement && dr.celement.controls.content ? dr.celement.controls.content.controls.subcontent.container : dr.element).childNodes;
            for (var i = 0; i < items.length; i++)
            {
                var ch = items[i];
                var v = ch.getAttribute && ch.getAttribute('value') ? ch.getAttribute('value') : '';
                if(v)
                {
                    if(v == value)
                    {
                        Extensions.AddCssClass(ch, 'sel');
                        var sText = '';
                        if((v == '0' || v == '') && dr.showHeaderTextOnEmpty)
                        {
                            sText = dr.header;
                        }
                        else sText = ch.innerHTML;
                         
                        (this.cobject && this.cobject.controls.core ? this.cobject.controls.core.container : (dr && dr.ccontrol && dr.ccontrol.controls.core ? dr.ccontrol.controls.core.container : this)).innerHTML = sText;
                    }
                    else Extensions.RemoveCssClass(ch, 'sel');
                }
            }
            dr.parent.setAttribute('sel', value);
            
            if(!suppressOnChangeEvent && dr.onItemSelected)
                dr.onItemSelected(value);
        }
    }
    
    this.FindDropdown = function(el)
    {
        for (var i = 0; i < this.dropdownObjects.length; i++)
        {
            var it = this.dropdownObjects[i];
            if(it.clicker == el || it.parent == el)
            {
                return it;
            }
        }
        return null;
    }
    this.ProcessDropdown = function(params, bShowAnyway)
    {
        this.InitializeDropdownsManagement();
        
        this.InitializeDropdown(params.parent);
        
        var obj = null;
        var el = params.clicker || params.parent;
        for (var i = 0; i < this.activeDropdownObjects.length; i++)
        {
            var it = this.activeDropdownObjects[i];
            if(it.clicker == el || it.parent == el)
            {
                if(bShowAnyway != true && params.showAnyway != true)
                {
                    this.CancelDropdownProcessing(it.element);
                    return;
                }
            }
            else 
            {
                if(!this.CancelDropdownProcessing(it.element))
                    return false;
            }
        }
        
        obj = this.FindDropdown(el);
        if(obj == null)
        {
            obj = new Object();
        }
        if(!obj.ccontrol)
        {
            obj.ccontrol = params.parent.cobject || CManager.ParseCControl(params.parent, null, null, null);

            obj.element = params.element || (obj.ccontrol.params.cont ? $get(obj.ccontrol.params.cont) : null);
            obj.celement = CManager.ParseCControl(obj.element, null, null, null);
            
            obj.parent = (obj.ccontrol.params.parentid ? $get(obj.ccontrol.params.parentid) : null) || params.parent || params.clicker;
            obj.clicker = params.clicker || params.parent;
            obj.callback = params.callback;
            obj.scrolled = params.scroller;
            obj.isLeftAligned = params.leftAligned != false;
            obj.hideOnInnerClick = params.hideOnInnerClick != false || obj.ccontrol.params.static == '1';
            obj.active = true;
            obj.showAnyway = params.showAnyway;
            obj.onOpening = params.onOpening || (obj.ccontrol.params.onOp ? eval(obj.ccontrol.params.onOp) : null);
            obj.changable = obj.parent.getAttribute('changable') != '0' && obj.ccontrol.params.changable != '0';
            obj.onItemSelected = obj.parent.getAttribute('onselected') || obj.ccontrol.params.onSel || '';
            if(obj.onItemSelected)
                obj.onItemSelected = eval(obj.onItemSelected);
            obj.showHeaderInElement = obj.ccontrol.params.showHeader == '1';
            obj.showHeaderTextOnEmpty = obj.ccontrol.params.hdrOnEmpty == '1';
            obj.header = obj.ccontrol.params.header || '';
        }
        
        if(Extensions.dropdownAction)
        {
            Extensions.dropdownAction.stop();
            Extensions.dropdownAction = null;
            SetElementTransparency(obj.element, null);
        }

        obj.element.style.display = '';
        if(obj.changable && !obj.elementsManaged && !obj.ccontrol.params.parentid) // ... and if not custom dd
        {
            obj.elementsManaged = true;
            
            var element = obj.celement && obj.celement.controls.content ?  obj.celement.controls.content.controls.subcontent.container : obj.element;
            var nodes = Extensions.GetChildNodes(element);
            if(nodes.length > 0)
            {
                var maxWidth = 0;
                var maxWidthIn = 0;
                
                for (var i = 0; i < nodes.length; i++)
                {
                    var nd = nodes[i];
                    var w = nd.offsetWidth - Extensions.GetCssProperty(nd, 'paddingLeft', 0) - Extensions.GetCssProperty(nd, 'paddingRight', 0);
                    if(w > maxWidthIn)
                        maxWidthIn = w;
                        
                    w = nd.offsetWidth + Extensions.GetCssProperty(nd, 'marginLeft', 0) + Extensions.GetCssProperty(nd, 'marginRight', 0) + 2;
                    if(w > maxWidth)
                        maxWidth = w;
                        
                    var h = nd.offsetHeight + Extensions.GetCssProperty(nd, 'marginTop', 0) + Extensions.GetCssProperty(nd, 'marginBottom', 0);
                }
                
                if(obj.clicker.offsetWidth > maxWidth * obj.columns)
                {
                    var diff = Math.ceil((obj.clicker.offsetWidth - maxWidth * obj.columns) / obj.columns);
                    maxWidth += diff;
                    maxWidthIn += diff;
                }
                for (var i = 0; i < nodes.length; i++)
                {
                    var nd = nodes[i];
                    nd.style.width = maxWidthIn + 'px';
                }
                
                obj.element.style.width = ((maxWidth - 0)* obj.columns) + 'px';
                element.style.height = (h * (Math.ceil(nodes.length / obj.columns))) + 'px';
            }
        }
            
        var h = null;
        if(obj.celement && obj.celement.controls.content)
        {
            k = obj.celement.controls.content.container.offsetHeight;
            h = obj.celement.container.offsetHeight;
            obj.celement.controls.content.container.style.height = '0';
            obj.celement.controls.content.container.style.overflow = 'hidden';
            obj.celement.controls.content.controls.subcontent.container.style.position = 'relative';
            if(obj.celement.controls.header)
            {
                obj.celement.controls.header.controls.subheader.container.style.position = 'relative';
                obj.celement.controls.header.container.style.overflow = 'hidden';
                actM.addAction(new action(obj.celement.controls.header.controls.subheader.container, 0, obj.celement.controls.header.container.offsetHeight, '{0}.style.top=(-' + obj.celement.controls.header.container.offsetHeight + '+{1})+"px";{0}.parentNode.style.height="{1}px"', 75, -100, function(_e)
                {
                    _e.style.height = '';_e.parentNode.style.height = '';
                    actM.addAction(new action(obj.celement.controls.content.controls.subcontent.container, 0, k, '{0}.style.top=(-' + k + '+{1})+"px";{0}.parentNode.style.height="{1}px"', 105, -100, function(_e2){/*_e2.style.height = '';_e2.parentNode.style.height = '';*/}, null, 15));
                }, null, 15));
            }
            else
            {
                actM.addAction(new action(obj.celement.controls.content.controls.subcontent.container, 0, k, '{0}.style.top=(-' + k + '+{1})+"px";{0}.parentNode.style.height="{1}px"', 105, -100, function(_e2){/*_e2.style.height = '';_e2.parentNode.style.height = '';*/}, null, 15));
            }
        }
        
        obj.element.style.position = 'absolute';
        obj.element.style.zIndex = params.zIndex || '999999';
        
        document.body.insertBefore(obj.element, null);
        
        Extensions.AddCssClass(obj.clicker, 'open');
        
        if(!this.activeDropdownObjects.exists(obj))
            this.activeDropdownObjects.push(obj);
        
        this.ProcessDropdownPosition(obj, h);
        
        if(obj.onOpening)
            obj.onOpening(params);
            
        return true;
    }
    this.ProcessDropdownPosition = function(obj, iDropdownHeight)
    {
        var off = getElementOffset(obj.parent);
        iDropdownHeight = iDropdownHeight || obj.element.offsetHeight;
        if(off.top + obj.parent.offsetHeight + iDropdownHeight < getWindowSize().height)
            obj.element.style.top = (off.top + obj.parent.offsetHeight) + 'px';
        else
            obj.element.style.top = (off.top - iDropdownHeight) + 'px';
            
        var x = off.left;
        if(!obj.isLeftAligned)
            x += obj.parent.offsetWidth - obj.element.offsetWidth;
        obj.element.style.left = x + 'px';
    }
    this.DropdownManagementHandler = function(e)
    {
        if(this.activeDropdownObjects.length > 0)
        {
            var obj = this.activeDropdownObjects[0];
            var p = (e && e.target ? e.target : event.srcElement);
            var src = p;
            var itemWasChanged = false;
            while(p)
            {
                if(p == obj.element)
                {
                    if(obj.changable)
                    {
                        obj.parent.setValueEx(src.getAttribute('value'));
                    }

                    itemWasChanged = true;
                    
                    if(!obj.hideOnInnerClick)
                        break;
                }
                
                if(p == obj.parent)
                    return;
                    
                p = p.parentNode;
            }
            if(!p)
            {
                var bContinueCancel = obj.callback ? (obj.callback(obj) != false) : true;
                if(bContinueCancel)
                {
                    this.CancelDropdownProcessing(obj.element, true, itemWasChanged);
                }
            }
        }
    }
    this.DropdownManagementDownHandler = function(e)
    {
        if(this.activeDropdownObjects.length > 0)
        {
            var obj = this.activeDropdownObjects[0];
            var p = (e && e.target ? e.target : event.srcElement);
            while(p)
            {
                if(p == obj.element)
                    return;
                    
                if(p == obj.parent)
                    return;
                    
                p = p.parentNode;
            }
            if(!p)
            {
                var bContinueCancel = obj.callback ? (obj.callback(obj) != false) : true;
                if(bContinueCancel)
                {
                    this.CancelDropdownProcessing(obj.element, true);
                } 
                else
                {
                    e = e || window.event;
                    e.cancelBubble = true;
                    e.returnValue = false;
                    
                    return false;
                }
            }
        }
    }
    this.DropdownManagementScrollHandler = function(e)
    {
        if(this.activeDropdownObjects.length > 0)
        {
            var obj = this.activeDropdownObjects[0];
            this.ProcessDropdownPosition(obj);
        }
    }
    this.CancelDropdownProcessing = function(element, forceCancelling, itemWasChanged)
    {
        for (var i = 0; i < this.activeDropdownObjects.length; i++)
        {
            var it = this.activeDropdownObjects[i];
            if(it.element == element)
            {
                if(it.callback && !forceCancelling)
                {
                    if(it.callback(it) == false)
                        return false;
                }
                
                Extensions.RemoveCssClass(it.clicker, 'open');
                if(!this.dropdownObjects.findObject(element))
                    this.dropdownObjects.push(it);
                this.activeDropdownObjects.splice(i, 1);
                
                if(this.activeDropdownObjects.length == 0)
                {
                    this.dropdownAction = new action(it.element, 100, 0, 'opacity', itemWasChanged ? 250 : 75, 0, function(_e2){if(Extensions.activeDropdownObjects.length == 0){_e2.style.display = 'none';SetElementTransparency(_e2, null);Extensions.dropdownAction = null;}}, null, 15);
                    actM.addAction(this.dropdownAction);
                }
                //it.element.style.display = 'none';
                return true;
            }
        }
        return true;
    }
    
    
    /* other */
    this.AddCssClass = function(element, sCssClass)
    {
        var classes = (element.className || '').split(' ');
        if(classes.exists(sCssClass))
            return;

        classes.push(sCssClass);
        element.className = classes.join(' ');
    }
    this.RemoveCssClass = function(element, sCssClass)
    {
        var classes = (element.className || '').split(' ');
        for (var i = classes.length - 1; i >= 0; i--)
        {
            var cl = classes[i];
            if(cl == sCssClass)
                classes.splice(i, 1);
        }
        element.className = classes.join(' ');
    }
    this.ReplaceCssClass = function(itemClassName, ruleClassName, replaceToClassName)
    {
        var result = itemClassName;
        if(itemClassName && ruleClassName)
        {
            var classes = itemClassName.split(' ');
            var classesReplace = ruleClassName.split(' ');
            var classesReplaceTo = replaceToClassName.split(' ');
            
            for(var i = classes.length - 1; i >= 0; i--)
            {
                for (var j = 0; j < classesReplace.length; j++)
                {
                    if(classes[i] == classesReplace[j])
                    {
                        classes.splice(i, 1);
                        break;
                    }
                }
            }
            
            for(var i = classes.length - 1; i >= 0; i--)
            {
                for (var j = classesReplaceTo.length - 1; j >= 0; j--)
                {
                    if(classes[i] == classesReplace[j])
                    {
                        classesReplaceTo.splice(j, 1);
                        continue;
                    }
                }
            }
            
            for (var i = 0; i < classesReplaceTo.length; i++)
            {
                var cl = classesReplaceTo[i];
                classes.push(cl);
            }
            
            result = classes.join(' ');
        }
        
        return result;
    }

    this.HasCssClass = function(element, sCssClass)
    {
        var classes = (element.className || '').split(' ');
        return classes.exists(sCssClass);
    }
    
    this.GetChildNodes = function(node, nodeName)
    {
        if(nodeName)
            nodeName = nodeName.toLowerCase();
            
        var items = new Array();
        if(node.childNodes)
        {
            for(var i = 0; i < node.childNodes.length; i++)
            {
                var it = node.childNodes[i];
                if(it.nodeType == 1 && (!nodeName || (it.tagName || '').toLowerCase() == nodeName))
                    items.push(it);
            }
        }
        else alert('Extensions.GetChildNodes: the object doesn\'t contain childNodes collection.');
        
        return items;
    }


   
    this.getInputBoxValue = function()
    {        
        if(mbi.extensions.HasCssClass(this, 'empty'))
            return '';
        else
            return this.value;
    }
    this.setInputBoxValue = function (value)
    {
        value = value || '';
        if (value)
        {
            mbi.extensions.RemoveCssClass(this, 'empty');
            this.value = value;
        }
        else if(this.getAttribute('placeHolder'))
        {
            this.value = this.getAttribute('placeHolder');
            mbi.extensions.AddCssClass(this, 'empty');
        }
        else this.value = value;
    }
    this.inputBoxInit = function (p)
    {
        if (p.getAttribute('placeHolder'))
        {
            if (!mbi.extensions.HasCssClass(p, 'empty') && !p.value)
            {
                mbi.extensions.AddCssClass(p, 'empty');
                p.value = p.getAttribute('placeHolder');
            }
        }
    }
    this.onInputBoxBlur = function(e)
    {
        var p = e && e.target ? e.target : event.srcElement;
        if(p.value == '')
        {
            mbi.extensions.AddCssClass(p, 'empty');
            p.value = p.getAttribute('placeHolder');
        }
        mbi.extensions.RemoveCssClass(p, 'active');
    }
    this.onInputBoxFocus = function(e)
    {
        var p = e && e.target ? e.target : event.srcElement;
        
        if(mbi.extensions.HasCssClass(p, 'empty'))
        {
            p.value = '';
            mbi.extensions.RemoveCssClass(p, 'empty');
        }
        mbi.extensions.AddCssClass(p, 'active');
    }

    this.GetCssProperty = function(el, sJsStyleProperty, bGetValueAsInt)
    {
        var result = '';
        if (el.currentStyle) //IE
            result = el.currentStyle[sJsStyleProperty];
        else if (document.defaultView && document.defaultView.getComputedStyle) //Firefox
            result = document.defaultView.getComputedStyle(el, "")[sJsStyleProperty];
        else //try and get inline style
            result = el.style[cssprop];
            
        if(bGetValueAsInt == 0 || bGetValueAsInt)
        {
            var i = 0;
            i = parseInt(result);
            if(isNaN(i))
                i = 0;
            return i;
        }
        else return result;
    }
    
    this.GPageMethodErrorHandler = function(result)
    {
        alert(result.get_message());
    }
    
    
    /* buttons handling */
    this.IsButtonsHandlingInitialized = false;
    this.InitializeButtonsHandling = function()
    {
        if(!this.IsButtonsHandlingInitialized)
        {
            this.IsButtonsHandlingInitialized = true;
            AddBrowserHandler(document, "mousedown", function(e){return Extensions.ButtonMouseDownHandler(e);});
            this.InitializeButtonsHandlingEx();
        }
    }
    this.InitializeButtonsHandlingEx = function()
    {
            MManager.addClassHandler('GHButton', function(sender, source){Extensions.ButtonMouseOverHandler(sender, source);}, function(sender){Extensions.ButtonMouseOutHandler(sender);}, null);
            AddBrowserHandler(document, "mouseup", function(e){return Extensions.ButtonMouseUpHandler(e);});
    }
    this.CurrentActiveButton = null;
    this.ButtonMouseDownHandler = function(e)
    {
        if(this.CurrentActiveButton)
        {
            this.DeactivateCurrentButton();
        }
        var p = (e && e.target ? e.target : event.srcElement);
        while(p)
        {
            if(Extensions.HasCssClass(p, 'GHButton'))
            {
                if(Extensions.HasCssClass(p, 'disabled'))
                    return false;
                    
                break;
            }
            p = p.parentNode;
        }
        if(p)
        {
            this.CurrentActiveButton = p;
            p.unselectable = true;
            p.onselectstart = function(){return false;};
            
            if (typeof p.style.MozUserSelect != "undefined")
                p.style.MozUserSelect = "none";
    
            Extensions.AddCssClass(p, 'pressed');
            Extensions.AddCssClass(p, 'activated');
            
            e = e || window.event;
            e.cancelBubble = true;
            e.returnValue = false;
            
            return false;
        }
    }
    this.ButtonMouseUpHandler = function(e)
    {
        if(this.CurrentActiveButton)
        {
            var p = (e && e.target ? e.target : event.srcElement);
            while(p)
            {
                if(Extensions.HasCssClass(p, 'GHButton'))
                {
                    break;
                }
                p = p.parentNode;
            }
            
            this.DeactivateButton();

            if(p != this.CurrentActiveButton)
            {
                return false;
            }
        }
    }
    this.DeactivateButton = function()
    {
        Extensions.RemoveCssClass(this.CurrentActiveButton, 'pressed');
        Extensions.RemoveCssClass(this.CurrentActiveButton, 'activated');
        this.CurrentActiveButton = null;
    }
    this.ButtonMouseOverHandler = function(sender, source)
    {
        if(this.CurrentActiveButton == sender)
        {
            Extensions.AddCssClass(sender, 'pressed');
        }
    }
    this.ButtonMouseOutHandler = function(sender)
    {
        if(this.CurrentActiveButton == sender)
        {
            Extensions.RemoveCssClass(sender, 'pressed');
        }
    }
    
    this.ProcessDefaultButton = function(e, sClientID)
    {
        var k = e.keyCode ? e.keyCode : e.charCode ? e.charCode : e.which ? e.which : 0;
        var p = e.target || e.srcElement;
        if(k == 13)
        {
            if(p && (p.tagName || '').toLowerCase() == 'textarea')
            {
                return;
            }
            else
            {
                activateClickEvent($get(sClientID));
                return false;
            }
        }
    }
    
    this.InputContainerWatcherInitialized = false;
    this.AddInputContainerWatcher = function()
    {
        if(!this.InputContainerWatcherInitialized)
        {
            this.InputContainerWatcherInitialized = true;
            MManager.addClickHandler(null, function(e, source, sender){ Extensions.AddInputContainerHandler(e, source, sender);}, 'GHInputContainer');
        }
    }
    this.AddInputContainerHandler = function(e, source, sender)
    {
        if(source == sender)
        {
            if(sender.getElementsByTagName('input')[0])
                sender.getElementsByTagName('input')[0].focus();
        }
    }

    this.manageInputs = function(container)
    {
        var inputs = container ? $(container).find('input[type="text"]') : $('input[type="text"]');
        for (var i = 0; i < inputs.length; i++)
        {
            var it = inputs[i];
            if(it.getAttribute('placeHolder') && !it.cobject)
            {
                mbi.cmanager.ParseCControl(it);    
            }
        }

    }

    mbi.core.event(window, 'load', function ()
    {
        if (mbi.global.menuExists)
        {
            mbi.handlers.cls('gh-menu', null, function (sender)
            {
                $(sender).find('.not-hovered').toggleClass('not-hovered', false);
                $(sender).find('.hovered').toggleClass('hovered', false);
                $(sender).find('.open').toggleClass('open', false);
                $(sender).find('.g-submenu').css('display', 'none');
                $(sender).find('.g-submenu.active').css('display', '');
            }, null, null, 50);
            mbi.handlers.cls('gh-menu-item', function (sender, source)
            {
                $(sender.parentNode).find('.g-submenu').css('display', 'none');
                $(sender.parentNode).find('.gh-menu-item').toggleClass('not-hovered', true);
                $(sender.parentNode).find('.open').toggleClass('open', false);
                $(sender).toggleClass('not-hovered', false);
                $(sender).toggleClass('open', true);
                $(sender.parentNode).find('.g-submenu').toggleClass('hovered', false);
                var cls = sender.className.split(' ');
                for (var i = 0; i < cls.length; i++)
                {
                    if (cls[i].indexOf('g-menu-') == 0)
                    {
                        var cl = 'g-submenu-' + cls[i].substr(7);
                        $(sender.parentNode).find('.' + cl).css('display', '');
                        $(sender.parentNode).find('.' + cl).toggleClass('hovered', true);
                    }
                }
            }, null, null, 50);
        }
    });
}
function Extensions_DropdownManagementDownHandler(e) { return Extensions.DropdownManagementDownHandler(e); }
function Extensions_DropdownManagementHandler(e) { return Extensions.DropdownManagementHandler(e); }
function Extensions_DropdownManagementScrollHandler(e) { return Extensions.DropdownManagementScrollHandler(e); }

try { if(!Extensions){ Extensions = new ExtensionsManager();}  } catch (er) {Extensions = new ExtensionsManager(); }
mbi.Extensions = Extensions;
mbi.extensions = Extensions;
Extensions.InitializeButtonsHandling();

try
{
    HTMLInputElement.prototype.setValue = function(value){Extensions.setInputBoxValue.call(this, value);};
    HTMLInputElement.prototype.getValue = function(){return Extensions.getInputBoxValue.call(this);};
    //HTMLTextAreaElement.prototype.setValue = function(value){Extensions.SetEmptyBoxValue(this, value);};
    //HTMLTextAreaElement.prototype.getValue = function () { return Extensions.GetEmptyBoxValue(this); };
}
catch(er){}

if (!mbi.tools.autolist)
{
    mbi.tools.autolist = new Object();
    mbi.tools.autolist.currentSortingField = ''; // used for temporary Array.sort() function call
    mbi.tools.autolist.currentSortingAsc = false; // used for temporary Array.sort() function call

    mbi.tools.autolist.create = function (cContainer, cSearchBox,
    fsSearchComparer, fsSortingComparer, iPartialRenderingSize, fOnItemCreating,
    fsAjaxRequest, oOptions, oData)
    {
        var a = new GAutolistManager(cContainer, cSearchBox,
            fsSearchComparer, fsSortingComparer, iPartialRenderingSize, fOnItemCreating,
            fsAjaxRequest, oOptions);
        
        a.bind(oData || oOptions.data);
        return a;
    }

    /// public: Manages lists data sorting, searching and loading in auto/half-auto modes dependently on params.
    function GAutolistManager(cContainer, cSearchBox,
        fsSearchComparer, fsSortingComparer, iPartialRenderingSize, fOnItemCreating,
        fsAjaxRequest, oOptions)
    {
        this.options = oOptions || new Object();

        this.options.instance = this;

        this.data = null;// oData || this.options.oData;
        this.cache = null;
        this.content = null;

        this.options.container = cContainer || this.options.container;
        this.options.searchBox = cSearchBox || this.options.searchBox;

        this.options.searchComparer = this.options.searchComparer || fsSearchComparer;
        if (typeof (this.options.searchComparer) == 'string')
        {
            this.options.searchComparerField = fsSearchComparer;
        }
        else if (this.options.searchComparer)
            this.searchComparer = this.options.searchComparer;

        this.options.sortingComparer = this.options.sortingComparer || fsSortingComparer;
        if (typeof (this.options.sortingComparer) == null && typeof (fsSearchComparer) == 'string')
            this.options.sortingComparerField = fsSearchComparer;
        else if (typeof (fsSortingComparer) == 'string')
            this.options.sortingComparerField = fsSortingComparer;
        else if (this.options.sortingComparer)
            this.sortingComparer = this.options.sortingComparer;
        this.options.sortingAsc = this.options.sortingAsc || true;

        this.options.partialRenderingSize = iPartialRenderingSize || 0;
        this.options.onItemCreating = fOnItemCreating || this.options.onItemCreating;
        if (typeof (this.options.onItemCreating) == 'string')
        {
            this.options.itemTemplateName = this.options.onItemCreating;
        }
        else if (this.options.onItemCreating)
        {
            this.onItemCreating = this.options.onItemCreating;
        }
        else
        {
            this.options.itemTemplateName = this.container.params.template;
        }

        this.options.ajaxProcessor = this.options.ajaxProcessor || fsAjaxRequest;
        if (this.options.ajaxProcessor)
        {
            if (typeof (this.options.ajaxProcessor) == 'string')
                this.options.ajaxRequestName = this.options.ajaxProcessor;
            else
                this.ajaxProcessor = this.options.ajaxProcessor;
        }

        this.options.autoSearchWaitingTime = this.options.autoSearchWaitingTime || 350; // time in milliseconds - how much time to wait between keys pressing to refresh results. -1 means searching on search button click only
        this.options.searchButton = this.options.searchButton || (cSearchBox ? cSearchBox.cc.search : null);
        this.options.clearButton = this.options.clearButton || (cSearchBox ? cSearchBox.cc.clear : null);
        //this.options.clearingCallback
        //this.options.loadingContainer

        this.search = '';
        this.prevSearch = '';
    }

    GAutolistManager.prototype.searchComparer = function (sSearch, oData, oOptions)
    {

    }
    GAutolistManager.prototype.sortingComparer = function (oData1, oData2, oOptions)
    {

    }
    GAutolistManager.prototype.ajaxProcessor = function (oOptions)
    {

    }
    GAutolistManager.prototype.onAjaxProcessorOk = function (pmInfo, context)
    {
        //this.bind();
    }
    GAutolistManager.prototype.onItemCreating = function (oOptions)
    {

    }

    /// public: Clears Autolist content and fills with new Data.
    GAutolistManager.prototype.bind = function (oData)
    {
        this.cache = null;
        this.setData(oData);
        this.clearList();

        this.doSearch();
    }

    /// private: ...
    GAutolistManager.prototype.setData = function (oData)
    {
        this.sortData(oData);
        this.data = oData;
    }

    GAutolistManager.prototype.sortCache = function ()
    {
        // rearranges cache on data sorting change
    }

    /// private: ...
    GAutolistManager.prototype.sortData = function (oData)
    {
        if (this.options.sortingComparer)
        {
            mbi.tools.autolist.currentSortingField = this.options.sortingComparerField;
            mbi.tools.autolist.currentSortingAsc = this.options.sortingAsc;
            oData.sort(this.sortingComparer);
        }
        return oData;
    }

    /// private: ...
    GAutolistManager.prototype.prepareCache = function ()
    {
    }

    /// private: ...
    GAutolistManager.prototype.generateContent = function ()
    {
    }

    /// private: ...
    GAutolistManager.prototype.clearList = function ()
    {
        this.content.removeChildren();
    }

    /// public: ...
    GAutolistManager.prototype.initializeFromHtml = function ()
    {
        
    }

    /// public: ...
    GAutolistManager.prototype.doSearch = function ()
    {
        if (this.options.ajaxProcessor)
        {
            // do ajax processing
        }
        else
        {
            
        }
    }

    /// public: ...
    GAutolistManager.prototype.getMoreRows = function ()
    {
        
    }


}


/* search manager */
var GSearchManagerSortingCommand;
var GSearchManagerSortingDirection;
function GSearchManager(sSearchByDef, sSearchAscDef, oContainer, oSortingContainer, oSearchBox, oSearchButton, oClearButton,
    oFillerCallback, searchComparer, sortingComparer, customIDComparer, inputFilteringCallback, onClearingCallback, useHiddingInsteadRecreation, onItemCreating,
    iPartialRenderingSize, oPartialScrollingContainer
    )
{
    this.searchByDef = sSearchByDef;
    this.searchAscDef = sSearchAscDef;
    this.searchBy = sSearchByDef;
    this.searchAsc = sSearchAscDef;
    this.content = null;
    this.cache = null;
    
    this.search = '';
    
    this.container = oContainer;
    this.searchComparer = searchComparer || function(sSearch, b){return (b || '').toLowerCase().indexOf(sSearch) != -1};
    this.sortingComparer = sortingComparer;// || function(a, b){return a - b;};
    this.customIDComparer = customIDComparer || function(oIDs, b){return oIDs.contains(b);};

    this.inputFilteringCallback = inputFilteringCallback;
    this.onClearingCallback = onClearingCallback;

    this.onStateChanged = null;

    this.onItemCreating = onItemCreating;
    this.useHiddingInsteadRecreation = useHiddingInsteadRecreation || false;
    this.customIDs = null;
    
    this.fillerCallback = oFillerCallback;
    
    this.partialRenderingSize = iPartialRenderingSize || 0;
    this.partialRenderingFrom = 0;
    this.partialRenderingTo = this.partialRenderingSize;
    
    this.partialScrollingContainer = oPartialScrollingContainer;
    this.partialScrollingContainerOnScroll = function(e)
    {
        //if(fnc)
          //  fnc(e);
        
        var p = this.partialScrollingContainer.parentNode;
        if(p.scrollTop > this.partialScrollingContainer.offsetHeight - p.offsetHeight - 10)
        {   
            if(this.itemsDisplayed || this.itemsDisplayed.length + 1 >= this.partialRenderingFrom)
            {
                var items = this.processDisplayItems(this.content, this.partialRenderingFrom, this.partialRenderingFrom + this.partialRenderingSize);
                this.partialRenderingFrom += this.partialRenderingSize;
                if(!this.itemsDisplayed)
                    this.itemsDisplayed = new Array();
                    
                for (var i = 0; i < items.length; i++)
                {
                    this.itemsDisplayed.push(items[i]);
                }
            }
        }
    }
    if(this.partialScrollingContainer)
    {
        var fnc;
        if(this.partialScrollingContainer.parentNode.onscroll)
        {
            fnc = this.partialScrollingContainer.parentNode.onscroll;
        }
        var srchObj = this;
        this.partialScrollingContainer.parentNode.onscroll = function(e)
        {
            window.setTimeout(function(){srchObj.partialScrollingContainerOnScroll(e)}, 0);
        }
    }
    this.searchItemParentPropertyObjectName = null;
    this.applySortingToHeader = function()
    {
        if(this.sortingElements)
        {
            for(var i = 0; i < this.sortingElements.length; i++)
            {
                var it = this.sortingElements[i];
                Extensions.RemoveCssClass(it, 'asc');
                Extensions.RemoveCssClass(it, 'desc');
                
                if(it.getAttribute('autosearch') == this.searchBy)
                {
                    Extensions.AddCssClass(it, this.searchAsc ? 'asc' : 'desc');
                }
            }
        }
    }
    this.sortingContainer = oSortingContainer;
    this.sortingElements = null;
    if(this.sortingContainer)
    {
        this.sortingContainer.autosearchobj = this;
        this.sortingContainer.onclick = function(e)
        {
            var obj = new Object();
            var srch = GSearchManager.prototype.getAutoSearchObjectEx(e, obj);
            if(srch && obj.source)
                srch.doSorting(obj.source.getAttribute('autosearch'));
            return false;
        }
        
        this.sortingElements = new Array();
        for(var i = 0; i < this.sortingContainer.childNodes.length; i++)
        {
            var it = this.sortingContainer.childNodes[i];
            if(it.getAttribute && it.getAttribute('autosearch'))
                this.sortingElements.push(it);
        }
        this.applySortingToHeader();
    }
    this.searchBox = oSearchBox;
    this.searchButton = oSearchButton;
    this.clearButton = oClearButton;  
    if(this.searchButton)
    {
        this.searchButton.autosearchobj = this;
        this.searchButton.onclick = function(e)
        {
            var srch = GSearchManager.prototype.getAutoSearchObject(e);
            srch.doSearching(srch.searchBox ? srch.searchBox.value : null, null);
            return false;
        }
    }
    else if(this.searchBox)
    {
        this.searchBox.autosearchobj = this;
        var fnc = function(e)
        {
            
            GSearchManager.prototype.getAutoSearchObject(e).refresh();
            //return false;
        }
        this.searchBox.onkeyup = fnc;
        this.searchBox.onpaste = fnc;
        this.searchBox.oncut = fnc;
        this.searchBox.oninput = fnc;
    }
    
    if(this.clearButton)
    {
        this.clearButton.autosearchobj = this;
        this.clearButton.onclick = function(e)
        {
            GSearchManager.prototype.getAutoSearchObject(e).doClearing();
            return false;
        }
    }

    this.refresh = function ()
    {
        var value = '';
        if (this.searchBox)
            value = this.searchBox.getValue();
        if (!this.useHiddingInsteadRecreation)
            this.cache = null;
        this.doSearching(value, null);
    }
    
    this.doCustomFiltering = function(customIDs)
    {
        this.customIDs = customIDs;
        if(!this.useHiddingInsteadRecreation)
            this.cache = null;
        this.doSorting(null);
    }


    this.doSorting = function (sSearchBy)
    {
        var srch = this.searchBy;
        var srchA = this.searchAsc;

        if (sSearchBy != null)
        {
            if (sSearchBy != this.searchBy)
            {
                this.searchBy = sSearchBy;
                this.searchAsc = this.searchAscDef;
            }
            else
            {
                this.searchAsc = !this.searchAsc;
            }
        }
        if (srch != this.searchBy || srchA != this.searchAsc)
            this.applySortingToHeader();

        if (!this.cache)
        {
            this.prepareCache();
        }


        GSearchManagerSortingCommand = !isNaN(parseInt(this.searchBy)) ? parseInt(this.searchBy) : this.searchBy;
        GSearchManagerSortingDirection = this.searchAsc;

        if (this.sortingComparer)
        {
            this.cache.sort(this.sortingComparer);
        }
        this.fillItems(this.partialRenderingSize ? this.content : this.cache);
    }
    
    this.setContent = function(content, sSearchItemParentPropertyObjectName)
    {
        this.content = content;
        this.searchItemParentPropertyObjectName = sSearchItemParentPropertyObjectName; // when several lists use the same data
        this.doSearching('', true);
    }
    
    this.removeSearchItem = function(sSearchItemPropertyName, sValue)
    {
        if(!this.content)
            return;
            
        for (var i = 0; i < this.content.length; i++)
        {
            var it = this.content[i];
            if(it[sSearchItemPropertyName] == sValue)
            {
                if (it.tag)
                    RemoveNodeEx(it.tag)

                this.content.splice(i, 1);
                break;
            }
        }
        this.refresh();
    }
    
    this.doSearching = function(sSearch, bFirstLoadingMode)
    {
        this.searchPrev = this.search || '';
        
        if(sSearch != null)
            this.search = sSearch;
        
        if(!this.useHiddingInsteadRecreation)
            this.cache = null;
        if(bFirstLoadingMode)
        {
            if(this.useHiddingInsteadRecreation)
                this.prepareCache(true);
                
            this.fillItems(this.content);
        }
        else
        {
            this.doSorting(null);
        }
    }
    
    this.doClearing = function()
    {
        this.search = '';
        this.customIDs = null;
        if(this.searchBox)
        {
            this.searchBox.setValue('');
            this.searchBox.focus();
        }
        this.searchBy = this.searchByDef;
        this.searchAsc = this.searchAscDef;
        this.cache = null;
        if(this.onClearingCallback)
        {
            this.onClearingCallback(this);
        }
        this.doSorting(null);
    }
    
    this.addItem = function(item)
    {
        this.content.splice(0, 0, item);
        if(this.useHiddingInsteadRecreation)
        {
            //if(!this.partialRenderingSize)
            //{
                if(this.onItemCreating)
                {
                    var el = this.onItemCreating(item, this.container, 0);
                    if(this.searchItemParentPropertyObjectName)
                        item[this.searchItemParentPropertyObjectName] = el;
                    else item.tag = el;
                    el.parentNode.insertBefore(el, el.parentNode.childNodes[0]);
                }
                //cache.push(it);
            //}
        }
    }
    
    this.prepareCache = function(bCreateAnyway)
    {
        var cache = new Array();
        var sSearch = this.search.toLowerCase();
        for(var i = 0; i < this.content.length; i++)
        {
            var it = this.content[i];
            if(!this.useHiddingInsteadRecreation || bCreateAnyway)
            {
                if(!this.partialRenderingSize)
                {
                    if(this.onItemCreating)
                    {
                        var el = this.onItemCreating(it, this.container, i);
                        if(this.searchItemParentPropertyObjectName)
                            it[this.searchItemParentPropertyObjectName] = el;
                        else it.tag = el;
                    }
                    cache.push(it);
                }                
                //it.tag.style.display = this.searchComparer(sSearch, it) ? '' : 'none';
            }
            else if(this.searchComparer(sSearch, it))
            {
                cache.push(it);
            }
        }
        if(this.customIDs)
        {
            for(var i = cache.length - 1; i >= 0; i--)
            {
                var it = cache[i];
                if(!this.customIDComparer(this.customIDs, it, this))
                {
                    cache.splice(i, 1);
                }
            }
        }
        this.cache = cache;
        //refreshScrollsExtensions(null);
    }

    this.fillItems = function (items)
    {
        if (this.useHiddingInsteadRecreation)
        {
            //var bRefining = this.partialRenderingSize && this.searchPrev.length > 0 && this.searchPrev.substr(0, this.searchPrev.length - 2) == this.search;

            var iFrom = 0;
            var iTo = -1;
            var itemsEx = items;
            /*if(bRefining)
            {
            itemsEx = this.itemsDisplayed;
            }
            else*/
            if (this.itemsDisplayed)
            {
                for (var j = 0; j < this.itemsDisplayed.length; j++)
                {
                    var el = this.itemsDisplayed[j];
                    //var el = this.searchItemParentPropertyObjectName ? it[this.searchItemParentPropertyObjectName] : it.tag;
                    el.style.display = 'none';
                }
                this.itemsDisplayed = null;
            }
            if (this.partialRenderingSize)
                iTo = this.partialRenderingSize;

            var res = this.processDisplayItems(itemsEx, 0, iTo);
            if (this.partialRenderingSize)
            {
                this.itemsDisplayed = res;
            }
            this.partialRenderingFrom = 0;
        }
        else
        {
            if (this.fillerCallback)
            {
                this.fillerCallback(items, this.container);
            }
        }
        if (this.onStateChanged)
            this.onStateChanged();
    }

    this.processDisplayItems = function (items, iFrom, iTo)
    {
        var sSearch = this.search.toLowerCase();
        var res = new Array();
        var n = 0;
        for (var i = 0; i < items.length; i++)
        {
            var it = items[i];
            var bVisible = this.searchComparer(sSearch, it);
            var el = this.searchItemParentPropertyObjectName ? it[this.searchItemParentPropertyObjectName] : it.tag;
            if (bVisible)
            {
                if (n >= iFrom && !el && this.onItemCreating)
                {
                    el = this.onItemCreating(it, this.container, i);
                    if (this.searchItemParentPropertyObjectName)
                        it[this.searchItemParentPropertyObjectName] = el;
                    else it.tag = el;
                    res.push(el);
                }
                if (el)
                    el.style.display = '';
            }
            else if (el)
            {
                el.style.display = 'none';
            }

            if (iTo != -1 && n > iTo)
            {
                break;
            }

            if (bVisible)
            {
                n++;
                if (this.sortingComparer) // that means items can be repositioned in container dynamically
                    el.parentNode.insertBefore(el, null);

                if (n > iFrom)
                {
                    if (n % 2 == 0)
                        Extensions.RemoveCssClass(el, 'alt');
                    else
                        Extensions.AddCssClass(el, 'alt');
                }
            }
        }
        return res;
    }
}
GSearchManager.prototype.getAutoSearchObject = function(e)
{
    var obj = new Object();
    return GSearchManager.prototype.getAutoSearchObjectEx(e, obj);
}

GSearchManager.prototype.getAutoSearchObjectEx = function(e, srchInvokerByRef)
{
    var p = (e && e.target ? e.target : event.srcElement);
    var el;
    while(p && p.autosearchobj == null)
    {
        if(p.getAttribute && p.getAttribute('autosearch'))
            el = p;
        
        p = p.parentNode;
    }
    
    if(srchInvokerByRef)
    {
        srchInvokerByRef.source = el;
        srchInvokerByRef.container = p;
    }
    return p.autosearchobj;
}



/* scrolling */
function ScrollingManager()
{
    this.scrollers = null;
    this.activeScrollBar = null;
    this.activeScroller = null;
    
    this.InitScroller = function(sClientID)
    {
        this.timer = null;
        if(!this.scrollers) // init
        {
            this.scrollers = new Array();

            AddBrowserHandler(document, 'mousemove', function(e){return ScrollingManager.ScrollerMouseMoveHandler(e);});
            AddBrowserHandler(document, 'mouseup', function(e){return ScrollingManager.ScrollerMouseUpHandler(e);});
            MManager.addClassHandler('GHScrollerBar', function(sender, source){return ScrollingManager.ScrollerBarOverHandler(sender, source);}, function(sender){return ScrollingManager.ScrollerBarOutHandler(sender);}, null);
            MManager.addClassHandler('GHScroller', function(sender, source){return ScrollingManager.ScrollerOverHandler(sender, source);},  function(sender){return ScrollingManager.ScrollerOutHandler(sender);}, null);
            
            if(window.addEventListener)
                window.addEventListener('DOMMouseScroll', function(e){return ScrollingManager.ScrollerOnMouseWheel(e);}, false);
            AddBrowserHandler(document, 'mousewheel', function(e){return ScrollingManager.ScrollerOnMouseWheel(e);});
                
            window.setTimeout(function(){ScrollingManager.RefreshScrollers();}, 500);
        }
        var el = $get(sClientID);
        var cobj = CManager.ParseCControl(el, null, null, null);
        
        this.scrollers.push(new GScrollerInstance(cobj, this));
        
    }

    this.RefreshScrollers = function()
    {
        for (var i = 0; i < this.scrollers.length; i++)
        {
            var scr = this.scrollers[i];
            if(scr.h)
                scr.UpdateCoreItemsWidth();
            
            
            if(scr.v && scr.v.prevHeight != scr.coreitems.offsetHeight 
                || scr.h && scr.h.prevWidth != scr.coreitems.offsetWidth)
            {
                if(scr.vscroller)
                {
                    scr.vscroller.style.height = scr.core.offsetHeight + 'px';
                    //scr.vscroller.style.marginTop = (-scr.core.offsetHeight) + 'px';
                }
                scr.ProcessScrollingState(true);
            }
        }
        window.setTimeout(function(){ScrollingManager.RefreshScrollers();}, 500);
    }
    
 
    function GScrollerInstance(cobject, manager)
    {
        this.manager = manager;
        this.cobject = cobject;
        this.cobject.tag = this;
        
        this.core = cobject.controls.core.container;
        this.coreitems = cobject.controls.core.controls.coreitems.container;
        this.vscroller = cobject.controls.vbar ? cobject.controls.vbar.container : null;
        this.vscrollercore = cobject.controls.vbar ? cobject.controls.vbar.controls.core.container : null;
        this.hscroller = cobject.controls.hbar ? cobject.controls.hbar.container : null;
        this.hscrollercore = cobject.controls.hbar ? cobject.controls.hbar.controls.core.container : null;
        
        this.UpdateCoreItemsWidth = function()
        {
            var items = Extensions.GetChildNodes(this.coreitems);
            var w = 0;
            for (var i = 0; i < items.length; i++)
            {
                var it = items[i];
                w += it.offsetWidth;   
            }
            if(w)
                this.coreitems.style.width = w + 'px';
        }
        
        this.v = null;
        if((cobject.params.vmode || 0) != 0)
        {
            this.v = new Object();
            this.v.mode = cobject.params.vmode;
            this.v.auto = this.v.mode == 1 || this.v.mode == 3;
            this.v.manual = (this.v.mode == 2 || this.v.mode == 3) && !!cobject.controls.vbar;
            this.v.barmode = cobject.params.vbarmode;
            this.v.speed = cobject.params.vspeed || 0;
            this.v.multi = cobject.params.vacc == 0 ? 0 : cobject.params.vacc || 100;
            this.v.acc = 0;
            this.v.acc2 = 0;
            this.v.prevHeight = null;//this.coreitems.offsetHeight;
            if(this.vscrollercore)
            {
                this.v.initialScrollerCoreWidth = this.vscrollercore.offsetWidth;
                this.vscroller.style.height = this.core.offsetHeight + 'px';
            }
            //this.vscroller.style.marginTop = (-this.core.offsetHeight) + 'px';
            this.v.vertical = true;
        }
        this.h = null;
        if((cobject.params.hmode || 0) != 0)
        {
            this.UpdateCoreItemsWidth();
            this.h = new Object();
            this.h.mode = cobject.params.hmode;
            this.h.auto = this.h.mode == 1 || this.h.mode == 3;
            this.h.manual = (this.h.mode == 2 || this.h.mode == 3) && !!cobject.controls.hbar;
            this.h.barmode = cobject.params.hbarmode;
            this.h.speed = cobject.params.hspeed || 0;
            this.h.multi = cobject.params.hacc == 0 ? 0 : cobject.params.hacc || 100;
            this.h.acc = 0;
            this.h.acc2 = 0;
            this.h.prevWidth = null;
            
            this.h.horizontal = true;
        }
        if(this.v && cobject.controls.vbar)
            cobject.controls.vbar.tag = this.v;
        if(this.h && cobject.controls.hbar)
            cobject.controls.hbar.tag = this.h;
            
        var elements = new Array();
        if(this.v && this.v.manual)
            elements.push(cobject.controls.vbar.container);
        if(this.h && this.h.manual)
            elements.push(cobject.controls.hbar.container);

        if(elements.length > 0)
        {
            var fnc = function(e)
            {
                var p = (e && e.target ? e.target : event.srcElement);
                if(p.cobject.name == 'core')
                {
                    var pr = new Object();
                    pr.sender = p;
                    pr.container = p.parentNode;
                    //pr.onStopDragging = function(params){ stopProcessing = false; } // it's processed by document at the moment
                    pr.callBack = function(e, sender)
                    {
                        var scrlr = sender.cobject;scrlr.parent.parent.tag.ProcessScrollingFromScrollerBar(scrlr.parent); 
                    }
                    DNDManager.startDragging(pr);
                    ScrollingManager.activeScrollBar = p.cobject.parent;
                    return false;
                }
                else
                {
                    // there is scrolling down/up must be processed
                }
            }
            for (var i = 0; i < elements.length; i++)
            {
                var el = elements[i];
                el.onmousedown = fnc;
            }
        }

        this.ProcessAutoscrollingParams = function(bOut)
        {
            if(ScrollingManager.activeScrollBar)
                return;
            
            if(this.v && this.v.auto)
            {
                var _y = yMousePos - getElementOffset(this.core).top - this.core.scrollTop;
                var _h = this.core.offsetHeight;
                var _h2 = this.coreitems.offsetHeight;
                
                if(_h2 == 0 && _h == 0)
                {
                    this.v.prevHeight = 0;
                }
                else if(_h2 < _h)
                {
                    this.v.prevHeight = _h2;
                }
                else if(bOut)
                {
                    this.v.acc2 = 0;
                }
                else
                {
                    var _p = Math.round(_y / _h * 100) - 50;
                    _p = _p * 1;

                    this.v.acc2 = _p * Math.abs(_p) / (ie ? 5 : 8);
                }
            }

            if(this.h && this.h.auto)
            {
                var _x = xMousePos - getElementOffset(this.core).left - this.core.scrollLeft;
                var _w = this.core.offsetWidth;
                var _w2 = this.coreitems.offsetWidth;
                
                if(_w2 == 0 && _w == 0)
                {
                    this.h.prevWidth = 0;
                }
                else if(_w2 < _w)
                {
                    this.h.prevWidth = _w2;
                }
                else if(bOut)
                {
                    this.h.acc2 = 0;
                }
                else
                {
                    var _p = Math.round(_x / _w * 100) - 50;
                    _p = _p * 1;

                    this.h.acc2 = _p * Math.abs(_p) / (ie ? 5 : 8);
                }
            }
            this.ProcessScrollingState();
        }
        
        this.ProcessScrollingState = function(bRefresh)
        {
            var res = new Object();
            var bChanged = false;
            if(this.v && (this.v.mode != 2 || bRefresh))
            {
                var iTop = -(this.core.scrollTop || 0);
                if(this.v.mode == 4)
                {
                    if(ScrollingManager.activeScroller)
                    {
                        if(this.core.offsetHeight < this.coreitems.offsetHeight)
                        {
                            iTop = (getElementOffset(this.cobject.container).top - yMousePos) / this.core.offsetHeight;
                            iTop += (iTop > 0.5 ? -1 : 1) * iTop / 10;
                            iTop = Math.round((this.coreitems.offsetHeight - this.core.offsetHeight) * iTop);
                        }
                        else iTop = 0;
                    }
                }
                else
                {
                    var iOldTop = iTop;
                    var iHAll = this.coreitems.offsetHeight;
                    var iH = this.core.offsetHeight;
                    
                    var iAcc2Abs = 0;
                    var iSign = 1;
                    var iDiff = 0;
                    
                    if(this.v.acc < 0 && this.v.acc2 <= this.v.acc && iTop - this.v.acc / 15 * 5 > 2)
                    {
                        this.v.acc -= this.v.acc / 5;
                    }
                    else if(this.v.acc > 0 && this.v.acc2 >= this.v.acc && iTop - this.v.acc / 15 * 5 < -iHAll + iH - 2)
                    {
                        this.v.acc -= this.v.acc / 5;
                    }
                    else
                    {
                        iDiff = (this.v.acc2 - this.v.acc) / 5;
                        
                        if(Math.abs(iDiff) < 1)
                            this.v.acc = this.v.acc2;
                        else
                            this.v.acc += iDiff;
                    }

                    
                    iTop = (iTop - Math.round(this.v.acc / 15 * (this.v.multi / 100)));
                }
                if(iTop > 0)
                {
                    iTop = 0;
                    this.v.acc = 0;
                    res.vStopped = true;
                }
                else if(iTop < -iHAll + iH)
                {
                    iTop = -iHAll + iH;
                    this.v.acc = 0;
                    res.vStopped = true;
                }
                
                this.v.position = -iTop;
                bChanged = true;
            }
            
            if(this.h && (this.h.mode != 2 || bRefresh))
            {
                var iTop = -(this.core.scrollLeft || 0);
                if(this.v.mode == 4)
                {
                    if(ScrollingManager.activeScroller)
                    {
                        if(this.core.offsetWidth < this.coreitems.offsetWidth)
                        {
                            iTop = (getElementOffset(this.cobject.container).left - xMousePos) / this.core.offsetWidth;
                            iTop += (iTop > 0.5 ? -1 : 1) * iTop / 10;
                            iTop = Math.round((this.coreitems.offsetWidth - this.core.offsetWidth) * iTop);
                        }
                        else iTop = 0;
                    }
                }
                else
                {
                    var iOldTop = iTop;
                    var iHAll = this.coreitems.offsetWidth;
                    var iH = this.core.offsetWidth;
                    
                    var iAcc2Abs = 0;
                    var iSign = 1;
                    var iDiff = 0;
                    
                    if(this.h.acc < 0 && this.h.acc2 <= this.h.acc && iTop - this.h.acc / 15 * 5 > 2)
                    {
                        this.h.acc -= this.h.acc / 5;
                    }
                    else if(this.h.acc > 0 && this.h.acc2 >= this.h.acc && iTop - this.h.acc / 15 * 5 < -iHAll + iH - 2)
                    {
                        this.h.acc -= this.h.acc / 5;
                    }
                    else
                    {
                        iDiff = (this.h.acc2 - this.h.acc) / 5;
                        
                        if(Math.abs(iDiff) < 1)
                            this.h.acc = this.h.acc2;
                        else
                            this.h.acc += iDiff;
                    }

                    
                    iTop = (iTop - Math.round(this.h.acc / 15 * (this.h.multi / 100)));
                }

                if(iTop > 0)
                {
                    iTop = 0;
                    this.h.acc = 0;
                    res.hStopped = true;
                }
                else if(iTop < -iHAll + iH)
                {
                    iTop = -iHAll + iH;
                    this.h.acc = 0;
                    res.hStopped = true;
                }
                
                this.h.position = -iTop;
                bChanged = true;
            }
            
            if(bChanged)
            {
                this.RefreshScroller();
                
                if(this.timer && (!this.v || this.v.acc == 0 && this.v.acc2 == 0) && (!this.h || this.h.acc == 0 && this.h.acc2 == 0))
                {
                    window.clearInterval(this.timer);
                    this.timer = null;
                }
                else if(!this.timer && (this.v && (this.v.acc != 0 || this.v.acc2 != 0) || this.h && (this.h.acc != 0 || this.h.acc2 != 0)))
                {
                    var __this = this;
                    this.timer = window.setInterval(function(){__this.ProcessScrollingState(true);}, 25);
                }
            }
            return res;
        }
        
        this.RefreshScroller = function(bSuppressScrollerBarRefreshing)
        {
            var sCurrStyle = '';
            
            if(this.v)
            {
                var iH = this.core.offsetHeight;
                var iHAll = this.coreitems.offsetHeight;
                if(iHAll != this.v.prevHeight && this.v.mode != 4)
                {
                    this.v.position = 0;
                }

                var iTop = -this.v.position;
                
                if(this.v.position == this.v.prevPosition || this.v.prevHeight == iH)
                    return;
                
                this.v.prevHeight = iHAll;
                this.core.scrollTop = -iTop;
                
                if(this.vscroller)
                {
                    if(iTop < 0 && iHAll + iTop > iH)
                        sCurrStyle = ' middlepos';
                    else if(iTop < 0)
                        sCurrStyle = ' toppos';
                    else if(iHAll + iTop > iH)
                        sCurrStyle = ' bottompos';
                    else
                        sCurrStyle = '';
                        
                    
                    if(this.vscroller && !bSuppressScrollerBarRefreshing)
                    {
                        if(iHAll <= iH)
                        {
                            this.vscroller.style.display = 'none';
                        }
                        else
                        {
                            this.vscroller.style.display = '';
                            this.vscroller.style.height = iH + 'px';
                            this.vscroller.style.marginTop = (-iH) + 'px';
                            
                            var iScr = Math.round(iH * iH / (iHAll || 1));
                            var iScrDiff = iScr;
                            if(iScr < 25)
                                iScr = 25;
                            iScrDiff = iScr - iScrDiff;
                            this.vscrollercore.style.height = iScr + 'px';
                            var iScrTop = -Math.round((iH - iScrDiff) * iTop / ((iHAll || 1)));
                            if(iScrTop > iH - iScr)
                                iScrTop = iH - iScr;
                            this.vscrollercore.style.top = iScrTop + 'px';
                            //this.vscrollercore.style.width = this.vscroller.offsetWidth + 'px';
                        }
                    }
                }
            }
            
            if(this.h)
            {
                var iH = this.core.offsetWidth;
                var iHAll = this.coreitems.offsetWidth;
                if(iHAll != this.h.prevWidth && this.h.mode != 4)
                {
                    this.h.position = 0;
                }

                var iTop = -this.h.position;
                
                if(this.h.position == this.h.prevPosition || this.h.prevWidth == iH)
                    return;
                
                this.h.prevWidth = iHAll;
                this.core.scrollLeft = -iTop;
                
                if(this.hscroller)
                {
                    if(iTop < 0 && iHAll + iTop > iH)
                        sCurrStyle = ' centerpos';
                    else if(iTop < 0)
                        sCurrStyle = ' leftpos';
                    else if(iHAll + iTop > iH)
                        sCurrStyle = ' rightpos';
                    else
                        sCurrStyle = '';
                        
                    
                    if(this.hscroller && !bSuppressScrollerBarRefreshing)
                    {
                        if(iHAll <= iH)
                        {
                            this.hscroller.style.display = 'none';
                        }
                        else
                        {
                            this.hscroller.style.display = '';
                            this.hscroller.style.width = iH + 'px';
                            
                            var iScr = Math.round(iH * iH / (iHAll || 1));
                            var iScrDiff = iScr;
                            if(iScr < 25)
                                iScr = 25;
                            iScrDiff = iScr - iScrDiff;
                            this.hscrollercore.style.width = iScr + 'px';
                            var iScrTop = -Math.round((iH - iScrDiff) * iTop / ((iHAll || 1)));
                            if(iScrTop > iH - iScr)
                                iScrTop = iH - iScr;
                            this.hscrollercore.style.left = iScrTop + 'px';
                            //this.hscrollercore.style.width = this.vscroller.offsetWidth + 'px';
                        }
                    }
                }
            }
            
            this.cobject.container.className = 'GHScroller' + sCurrStyle;
        }
        this.RefreshScroller();
        
        this.ProcessScrollingFromScrollerBar = function(oScrollerBarObj)
        {
            var scrollerBar = oScrollerBarObj.container;
            var scroller = oScrollerBarObj.controls.core.container;
            
            if(oScrollerBarObj.tag.vertical)
            {
                this.v.acc = 0;
                this.v.acc2 = 0;
                
                this.v.position = Math.round((parseInt(scroller.style.top || 0)) / (scrollerBar.offsetHeight - scroller.offsetHeight) * Math.abs((this.core.offsetHeight - this.coreitems.offsetHeight)));
            }
            else
            {
                this.h.acc = 0;
                this.h.acc2 = 0;
                
                this.h.position = Math.round((parseInt(scroller.style.left || 0)) / (scrollerBar.offsetWidth - scroller.offsetWidth) * Math.abs((this.core.offsetWidth - this.coreitems.offsetWidth)));
            }
            
            this.RefreshScroller(true);
        }
        
        this.ProcessMouseWheel = function(delta, bShiftPressed)
        {
            var bResult = true;
            
            if(bShiftPressed)
            {
                if(this.h)
                    this.h.acc += -delta;
                else
                    return true;
            }
            else
            {
                if(this.v)
                    this.v.acc += -delta;
                else
                    return null;
            }
            
            //oCurrentlyActiveScrollWheelIssue.scrollParams.acc2 = 0;//-delta / 10;
            var res = this.ProcessScrollingState(true);
            if(bShiftPressed && res.hStopped || !bShiftPressed && res.vStopped)
            {
                bResult = null;
            }
            return bResult;
        }
    }

    this.ScrollerOverHandler = function(sender, source)
    {
        if(!this.activeScrollBar)
            sender.cobject.tag.ProcessAutoscrollingParams();//  processSongsMove(sender, false, null, null, null, source);
        this.activeScroller = sender.cobject.tag;
    }
    this.ScrollerOutHandler = function(sender)
    {
        if(!this.activeScrollBar)
            sender.cobject.tag.ProcessAutoscrollingParams(true);
            
        this.activeScroller = null;
    }
    this.ScrollerMouseMoveHandler = function()
    {
        if(this.activeScroller)
            this.activeScroller.ProcessAutoscrollingParams();
    }
    
    this.ScrollerMouseUpHandler = function(e)
    {
        if(this.activeScrollBar)
        {
            if(!this.activeScrollBarOver || this.activeScrollBarOver != this.activeScrollBar)
            {
                var obj = this.activeScrollBar.controls.core;
                if(obj.tag2)
                    obj.tag2.stop();
                if(this.activeScrollBar.tag.vertical)
                    obj.tag2 = new action(obj.container, 5, 0, '{0}.style.width=({1}*2+5)+"px";{0}.style.marginLeft=(-{1}+5)+"px";{0}.style.marginRight=(-{1}+5)+"px";', 45, 100, null, null, 15);
                else
                    obj.tag2 = new action(obj.container, 5, 0, '{0}.style.height=({1}*2+5)+"px";{0}.style.marginTop=(-{1}+5)+"px";{0}.style.marginBottom=(-{1}+5)+"px";', 45, 100, null, null, 15);
                actM.addAction(obj.tag2);
            }
            this.activeScrollBar = null;
        }
        if(this.activeScroller)
        {
            this.activeScroller.ProcessAutoscrollingParams();
        }
    }
    
    this.ScrollerBarOverHandler = function(sender, source)
    {
        this.activeScrollBarOver = sender.cobject;
        if(this.activeScrollBar)//searchIssuesScrollerAnimationOn)
        {
            return;
        }
        else if(this.activeScrollBarOver.tag && this.activeScrollBarOver.tag.manual)
        {
            var obj = sender.cobject.controls.core;
            if(obj.tag2)
                obj.tag2.stop();
            if(sender.cobject.tag.vertical)
                obj.tag2 = new action(obj.container, 0, 5, '{0}.style.width=({1}*2+5)+"px";{0}.style.marginLeft=(-{1}+5)+"px";{0}.style.marginRight=(-{1}+5)+"px";', 45, 100, null, null, 15);
            else
                obj.tag2 = new action(obj.container, 0, 5, '{0}.style.height=({1}*2+5)+"px";{0}.style.marginTop=(-{1}+5)+"px";{0}.style.marginBottom=(-{1}+5)+"px";', 45, 100, null, null, 15);
            actM.addAction(obj.tag2);
        }
    }
    this.ScrollerBarOutHandler = function(sender)
    {
        if(this.activeScrollBar)
        {
            this.activeScrollBarOver = null;
        }
        else if(this.activeScrollBarOver && this.activeScrollBarOver.tag && this.activeScrollBarOver.tag.manual)
        {
            var obj = sender.cobject.controls.core;
            if(obj.tag2)
                obj.tag2.stop();
            if(sender.cobject.tag.vertical)
                obj.tag2 = new action(obj.container, 5, 0, '{0}.style.width=({1}*2+5)+"px";{0}.style.marginLeft=(-{1}+5)+"px";{0}.style.marginRight=(-{1}+5)+"px";', 45, 100, null, null, 15);
            else
                obj.tag2 = new action(obj.container, 5, 0, '{0}.style.height=({1}*2+5)+"px";{0}.style.marginTop=(-{1}+5)+"px";{0}.style.marginBottom=(-{1}+5)+"px";', 45, 100, null, null, 15);
            
            actM.addAction(obj.tag2);
        }
        this.activeScrollBarOver = null;
    }

    this.ScrollerOnMouseWheel = function(e)
    {
        e = e || window.event;
        
        var bCancel = false;
        if(!this.activeScroller)
            return null;
        if(this.activeScrollBar)
            return false;
        
        if(bCancel)
        {
            /*if (e.preventDefault)
                e.preventDefault();
            e.cancelBubble = true;
            e.returnValue = false;*/
            return false;
        }
        
        var bShiftPressed = 0;
        if (parseInt(navigator.appVersion) > 3)
        {
            bShiftPressed = e.shiftKey;
        }
 
        var delta = 0;
        if (e.wheelDelta) 
        {
            delta = e.wheelDelta;// / 120;
            if (window.opera) delta = -delta;
        } 
        else if (e.detail) 
        {
            delta = -e.detail * 40;
        }
        
        if (delta)
        {
            if(this.activeScroller.ProcessMouseWheel(delta, bShiftPressed))
            {
                if (e.preventDefault)
                    e.preventDefault();
                e.cancelBubble = true;
                e.returnValue = false;
                return false;
            }
        }
    }
}
var ScrollingManager = new ScrollingManager();

