var openedPopup = null;
var popupZIndexCounter = 100;

function Popup(popupId,popupAnchor,positioningMode)
{
    this.popupId = popupId; 
    this.popupAnchor = popupAnchor;
    this.PositioningMode = positioningMode;
    this.closeOnClick = true;

    this.behavior = new AjaxControlToolkit.PopupBehavior($(popupId));
    this.behavior.initialize();

    this.show = show;
    this.hide = hide;
    
    function show(reset)
    {       
        if (reset) 
        {
           openedPopup = null;
        }
        
        
        // initilize popup
        popupZIndexCounter++;
        if (isIE())
        {
            //Gleb: removed in Atlas RC
            //popup.element.parentElement.style.zIndex = popupZIndexCounter;         
        }
                
        // initilize behavior to the popup 
        this.behavior.set_parentElement($(this.popupAnchor));
        this.behavior.set_positioningMode(this.PositioningMode);
        
        // hide opened popup
        if (openedPopup) 
        {
            var back = false;
            if (openedPopup.popupAnchor == this.popupAnchor
                && openedPopup.popupId == this.popupId)
            {
                back = true;                
            }               
            try{openedPopup.hide();}catch(e){}  
            
            if (back)
            {
                return;
            }     
        }        

        //debugger;
        this.behavior.show();
        openedPopup = this;            
        
        if (window.event!=null)
        {
            if (isIE())
            {
                window.event.cancelBubble = true; 
            }
            else
            {
                window.event.stopPropagation();
            }
        }
        document.onmousemove = this.closeOnClick ? checkPopups : null;    
        return false;
    }

    function hide(ev) 
    {
        document.onclick = null;
        openedPopup = null;
        this.behavior.hide();
    }
    
    this.dispose = function() {}

}



try
{
    Popup.registerClass('Popup', null, Sys.IDisposable);
}
catch(e){}



function ClosePopups()
{
    if (openedPopup) 
    {
        try{openedPopup.hide();}catch(e){}
    } 
}

function checkPopups()
{
    document.onmousemove = null;
    document.onclick = ClosePopups;
}


var previousOpened;

function ChangeTitle(control, firstTitle, secondTitle)
{
    if (previousOpened != null)
    {
        if (previousOpened != control)
        {
            previousOpened.title = firstTitle;
        }
    }
    
    if (control)
    {
        if (control.title)
        {
            if (control.title == firstTitle)
            {
                control.title = secondTitle;
            }
            else
            {
                control.title = firstTitle;
            }
        }
    }
    previousOpened = control;
}


