
function Principal()
{
    this.userId = -1;
    this.groupId = 7;
	this.isAdmin = false;
	this.isEmployee = false;
	
    this.cookieName = "Principal";
    this.glue = "|";
    
    var cookie = sjcl.cookie.read(this.cookieName);

    if (cookie != "")
    {
		var parts = cookie.split(this.glue);
		
		this.userId = parts[0];
		/*this.groupId = parts[1];
		this.isEmployee = parts[2];
		this.isAdmin = this.groupId == 1;*/
	}	
}

function UserProfile()
{
    this.version = "1.6";
    this.cookieName = "UserProfile";
    this.glue = "|";
    this.autoLogin = 0;
    this.loginName = "";
    this.expandRibbon = 1;
    
    var cookie = sjcl.cookie.read(this.cookieName);

    if (cookie != "")
        this._unpackage(cookie);
}

UserProfile.extend(
{
    update: function()
    {
        sjcl.cookie.write(this.cookieName, this._package(), 730, "/");
    },

    _package: function()
    {
        var parts = [
            this.version,
            this.autoLogin ? 1 : 0,
            this.loginName,
            this.expandRibbon ? 1 : 0
        ];
                     
        return parts.join(this.glue);                 
    },

    _unpackage: function(cookie)
    {
        var parts = cookie.split(this.glue);
        
        if (parts[0] == this.version)
        {
            if (parts[1] != undefined)
				this.autoLogin = parseInt(parts[1]);
			
			if (parts[2] != undefined)
				this.loginName = parts[2];
				
            if (parts[3] != undefined)
				this.expandRibbon = parts[3];
        }
    }
});

function LinkButton(id)
{
	this.id = id;
}

LinkButton.extend(
{
	title: function(str)
	{
		var e = $(this.id);
		var td = sjcl.dom.getChildByClassName(e, "Text");
		
		if (str != null)
			td.firstChild.data = str;
		else
			return td.firstChild.data;
	},
	
	description: function(str)
	{
		var e = $(this.id);
		var td = sjcl.dom.getChildByClassName(e, "Text");
		var div = sjcl.dom.getChildByTagName(td, "DIV");
		
		if (str != null)
		{
			if (!div)
			{
			    div = td.appendChild(document.createElement("DIV"));
			    div.className = "Description";
			    div.innerHTML = str;
			}
			div.innerHTML = str;
		}
		else
			return div ? div.innerHTML : "";
	}
});

function PageBar()
{
	this._showDelay = 100;
    this._hideDelay = 150;
}

PageBar.extend(
{
    attach: function(target) {
        if (!target)
            return;

        if (sjcl.dom.getStyle($("PageSubBar"), "display") == "none")
            return;

        this.target = target;

        var col = target.getElementsByTagName("*");

        for (var i = 0; i < col.length; i++) {
            var item = col[i];

            if (item.className.indexOf("Tab") != -1)
                sjcl.event.addMouseHoverEvents(item, this._onTabOver.bindAsEvent(this), this._onTabOut.bindAsEvent(this));

            if (item.className.indexOf("TabActive") != -1)
                this._activeTab = item;

            this._adjustMenuStripPos($(item.getAttribute("MenuStrip")), item);
        }

        var e = $("MenuStripsContainer");

        if (e) {
            this._div = document.createElement("DIV");
            this._div.innerHTML = "&nbsp;";
            this._div.style.display = "none";
            e.appendChild(this._div);

            sjcl.event.addMouseHoverEvents(e, this._onMenuStripsOver.bindAsEvent(this), this._onMenuStripsOut.bindAsEvent(this));
        }

        if (!this._getActiveMenuStrip())
            this._div.style.display = "";
    },

    tryRestore: function() {
        this._hideTimerId = window.setTimeout(this._restore.bind(this), this._hideDelay);
    },

    setMenuTitle: function(menuStrip, menu, title) {
        var ms = $(menuStrip);

        if (ms) {
            var e = sjcl.dom.getChildByAttributeValue(ms, "menu", menu);

            e.firstChild.nodeValue = title;
        }
    },

    _onTabOver: function(evt) {
        var event = new sjcl.Event(evt);
        var td = event.findByClassName("Tab");

        this.frozen = false;

        if (this._hideTimerId)
            window.clearTimeout(this._hideTimerId);

        this._showTimerId = window.setTimeout(this._doTabOver.bind(this, td), this._showDelay);
    },

    _onTabOut: function(evt) {
        if (this._showTimerId)
            window.clearTimeout(this._showTimerId);

        this._hideTimerId = window.setTimeout(this._restore.bind(this), this._hideDelay);
    },

    _onMenuStripsOver: function(evt) {
        this.msActive = true;

        if (this._hideTimerId)
            window.clearTimeout(this._hideTimerId);
    },

    _onMenuStripsOut: function(evt) {
        this.msActive = false;

        if (!this.frozen)
            this._hideTimerId = window.setTimeout(this._restore.bind(this), this._hideDelay);
    },

    _doTabOver: function(td) {
        if (this._lastTab == td)
            return;

        if (!this._lastTab && (td == this._activeTab))
            return;

        if (this._lastTab)
            this._hiliteTab(this._lastTab, false);

        if (td.className.indexOf("Active") == -1)
            this._hiliteTab(td, true);

        this._lastTab = td;

        this._hideMenuStrip(this._msLast);
        this._hideMenuStrip(this._getActiveMenuStrip());

        var ms = $(td.getAttribute("MenuStrip"));

        this._msLast = ms;
        this._showMenuStrip(ms, td);
    },

    _hiliteTab: function(tab, state) {
        if (tab.className.indexOf("Active") != -1)
            return;

        var filter = sjcl.browser.isIE7 ? sjcl.dom.getFilter(tab, "Fade") : null;

        filter && filter.apply();
        tab.className = state ? "Tab TabHover" : "Tab TabNormal";
        filter && filter.play();
    },

    _getActiveMenuStrip: function() {
        return this._activeTab ? $(this._activeTab.getAttribute("MenuStrip")) : null;
    },

    _adjustMenuStripPos: function(ms, tab) {
        if (ms) {
            var display = ms.style.display;

            ms.style.visibility = "hidden";
            ms.style.display = "";

            var rcTab = sjcl.dom.elementRect(tab);
            //sjcl.debug.dump(rcTab);
            var mid = rcTab.left + rcTab.width;

            var content = $('PageLayout');
            content = content.parentNode;

            shift = (sjcl.browser.clientWidth() - content.offsetWidth) / 2;

            if (ltr()) {
                var left = mid - ms.offsetWidth - shift;

                if (left > 0)
                    ms.style.marginLeft = left + "px";
            }
            else {
                var right = sjcl.browser.clientWidth() - mid + rcTab.width - ms.offsetWidth - shift;

                if (right > 0)
                    ms.style.marginRight = right + "px";
            }

            ms.style.display = display;
            ms.style.visibility = "visible";
        }
    },

    _showMenuStrip: function(ms, tab) {
        if (ms) {
            var filter = sjcl.browser.isIE7 ? sjcl.dom.getFilter(ms, "Fade") : null;

            this._div.style.display = "none";
            filter && filter.apply();
            ms.style.display = "";
            filter && filter.play();
        }
        else
            this._div.style.display = "";
    },

    _hideMenuStrip: function(ms) {
        if (ms)
            ms.style.display = "none";
    },

    _restore: function() {
        var ms = this._getActiveMenuStrip();

        if (ms == this._msLast)
            return;

        if (this._msLast)
            this._msLast.style.display = "none";

        if (this._lastTab)
            this._hiliteTab(this._lastTab, false);

        this._showMenuStrip(ms, this._activeTab);
        this._msLast = this._lastTab = null;
    }
});

function onPageMenuInit()
{
    g_PageBar.frozen = true;
}

function onPageMenuUninit()
{
    if (g_PageBar.frozen && !g_PageBar.msActive)
		g_PageBar.tryRestore();
		
	g_PageBar.frozen = false;	
}

function attachListView(lv)
{
	if (lv)
	{
	    var col = sjcl.dom.getElementsByClassName(lv, "Item Normal");
    	
	    for (var i = 0; i < col.length; i++)
		    sjcl.event.addMouseHoverEvents(col[i], onListViewOver, onListViewOut);
    }
}

function onListViewOver(evt)
{
	var event = new sjcl.Event(evt);
	var td = event.findByClassName("Item");
	var filter = sjcl.dom.getFilter(td, "Fade");
	
	filter && filter.apply();
	td.className = "Item Hover";
	filter && filter.play();
}

function onListViewOut(evt)
{
	var event = new sjcl.Event(evt);
	var td = event.findByClassName("Item");
	var filter = sjcl.dom.getFilter(td, "Fade");
	
	filter && filter.apply();
	td.className = "Item Normal";
	filter && filter.play();
}

function onButtonOver(e)
{
	e.className = "ButtonHover";
}

function onButtonOut(e)
{
	e.className = "ButtonNormal";
}

function onButtonDown(e)
{
	e.className = "ButtonActive";
}

function onButtonUp(e)
{
	e.className = "ButtonHover";
}

function navigateTo(url, event)
{
	if (event && event.ctrlKey)
		window.open(url, "_blank");
	else
		window.location = url;
}

function adjustBodyHeight(evt)
{
	var body = document.body;
	var html = document.body.parentNode;
	var content = $("ContentLayout");
	var delta = 1;
    var e;
    
    if (!content)
        return;
    
    if (e = $("PageHeader"))
        delta += e.offsetHeight;

    if (e = $("PageFooterMargin"))
        delta += e.offsetHeight;
        
    if (e = $("PageFooter"))
        delta += e.offsetHeight;

	if (sjcl.browser.isOpera)
	{
	    if (html.clientHeight < body.clientHeight)
		    content.style.height = (body.clientHeight - delta) + "px";
		else
		    content.style.height = (html.clientHeight - delta) + "px";
	}
	else
	{
	    if (html.clientHeight > body.clientHeight)
            content.style.height = (html.clientHeight - delta) + "px";
	}

	$("PageFooter").style.visibility = "visible";
}

function showWaitDialog(msg)
{
	if (!msg)
		msg = getString("PLEASE_WAIT") + "&nbsp;".repeat(25);
		
	return sjcl.widget.infoBox("", sjcl.path.mapNeutralImage('color_spinner.gif'), msg, true);
}

function setLocale(lang)
{
    var wd = showWaitDialog();
    var wr = new sjcl.net.WebRequest("/lib/ajax/SetLocale.php?lang=" + lang, 
        function()
        {
            wd.close();
            window.location.reload(true);
        }
    );
}

function toggle(img, id)
{
	var e = $(id);

	if (!e)
		return;

	if (sjcl.dom.getStyle(e, "display") == "none")
	{
		img.src = img.src.replace("plus", "minus");
		sjcl.dom.displayElement(e);
	}
	else
	{
		img.src = img.src.replace("minus", "plus");
		e.style.display = "none";
	}
	
	adjustBodyHeight();	
}

function toggleSectionBar(id, img)
{
    var e = $(id);
	var expanded = false;
	    
    if (e.style.display == "none")
    {
        e.style.display = "";
        img.src = img.src.replace("down", "up");
        expanded = true;
    }
    else
    {
        e.style.display = "none";
        img.src = img.src.replace("up", "down");
    }
    
    adjustBodyHeight();
    sjcl.net.load("/lib/ajax/SaveSectionBar.php?id=" + id + "&expanded=" + (expanded ? 1 : 0));
}

function toggleSearchPanel(a)
{
	var a = $("spToggleLink");
	var e = $("spDetails");
	
	if (a && e)
	{
		if (e.expanded)
		{
			e.style.display = "none";
			a.innerText = getString("ADVANCED");
			e.expanded = false;
		}
		else
		{
			var f1 = sjcl.dom.getFilter(e, "Fade");
			var f2 = sjcl.dom.getFilter(e, "Blinds");
			
			f1 && f1.apply();
			f2 && f2.apply();
			e.style.display = "block";
			f1 && f1.play();
			f2 && f2.play();
			
			a.innerText = getString("BASIC");
			e.expanded = true;
		}
	}
}

function showFeedsMenu(img, query, feedDir)
{
    var pos = location.pathname.lastIndexOf("/");
	var path = "/";
	var menu = g_ContextMenus.getMenu("mnuFeeds");
	var item;
	
	if (pos != -1)
		path = location.pathname.substring(0, pos + 1);
	
	if (feedDir)
	{
	    if (feedDir.indexOf("/") == 0)
	        feedDir = feedDir.substring(1);
    	    
	    if (feedDir.indexOf("/") == feedDir.length -1)
	        feedDir = feedDir.substring(0, feedDir.length - 1);
	
        path = "/" + feedDir + "/";
    }
    
	if (query.length > 0)
		query = "?" + query;
		
	item = menu.item(0);
	item.setUrl(path + "rss.php" + query);
	
	item = menu.item(1);
	item.setUrl(path + "atom.php" + query);

	g_ContextMenus.showContextMenu("mnuFeeds", img, null);
}

function EmailThisPage(title)
{
	window.location = "mailto:?subject=" + title + "&body=" + sjcl.escape(window.location.href);
}

function AddToFavorite(title)
{
	window.external.AddFavorite(window.location.href, title);
}

function PrintThisPage(id)
{
	var e = $(id);
	
	if (e)
		openPrintPreview(e.innerHTML);
}

function copyCodeBlock(id)
{
	var tbl = $(id);
	var bdy = tbl.firstChild;
	var sb = new sjcl.StringBuilder("\n");
	
	for (var tr = bdy.firstChild.nextSibling; tr; tr = tr.nextSibling)
		sb.write(tr.lastChild.innerText);
		
	sjcl.copyToClipboard(sb.toString());
}

function hsUpdateNavigation()
{
	var exp = hs.getExpander();
	var prev = hs.getAdjacentAnchor(exp.key, -1);
	var next = hs.getAdjacentAnchor(exp.key, 1);
	var o, tr;
	
	for (var i = 0; i < exp.overlays.length; i++)
	{
		var item = hs.$("hsId"+ exp.overlays[i]);
		
		if (item && item.getAttribute("TitleBar") == "1")
		{
			o = item;
			break;
		}
	}
	
	if (!o || (tr = sjcl.dom.getChildByTagName(o, "TR")) == null)
		return;
		
	var tdCap = sjcl.dom.firstChild(tr);
	var imgPrev = sjcl.dom.getChildByAttribute(tr, "Previous");
	var imgNext = sjcl.dom.getChildByAttribute(tr, "Next");
	var div = sjcl.dom.nextSibling(exp.a);
	
	if (div)
	{
		tdCap.innerText = div.innerText;
	}
	
	if (!imgPrev || !imgNext)
		return;
		
	if (prev)
	{
		imgPrev.src = imgPrev.src.remove("_dis");
		imgPrev.setAttribute("Enabled", "1");
		imgPrev.style.cursor = "pointer";
	}
	else
	{
		imgPrev.src = imgPrev.src.remove("_dis").replace(".png", "_dis.png");
		imgPrev.setAttribute("Enabled", "0");
		imgPrev.style.cursor = "default";
	}

	if (next)
	{
		imgNext.src = imgNext.src.remove("_dis");
		imgNext.setAttribute("Enabled", "1");
		imgNext.style.cursor = "pointer";
	}
	else
	{
		imgNext.src = imgNext.src.remove("_dis").replace(".png", "_dis.png");
		imgNext.setAttribute("Enabled", "0");
		imgNext.style.cursor = "default";
	}
}

function hsNext(e)
{
	if (e.getAttribute("Enabled") == "1")
		hs.next(e);
}

function hsPrevious(e)
{
	if (e.getAttribute("Enabled") == "1")
		hs.previous(e);
}

function wpBeforeEffect(e)
{
}

function wpAfterEffect(e)
{
	var fc = sjcl.dom.firstChild(e);
	
	e.style.overflow = "visible";
	e.style.position = "static";
	e.style.width = e.style.height = "";
	
	if (fc)
		fc.style.width = fc.style.height = "";
}


function RenderPopupNote(content, noteId, userId)
{
    noteId = (noteId != undefined)? noteId : 0;
    userId = (userId != undefined)? userId : 0;
    if(content != '')
    {
        var mainDiv = document.createElement('DIV');
        
        mainDiv.className = "PopupNote";   
        mainDiv.id = "PopupNote";
        
        var innerTable = document.createElement('TABLE');
        
        innerTable.className = "W100";
        innerTable.cellPadding = "0";
        innerTable.cellSpacing = "0";
        
        var innerTbody = document.createElement('TBODY');
        
        var tr = document.createElement('TR');
        
        var textTd = document.createElement('TD');
        
        textTd.style.width = "98%";
        
        var textDiv = document.createElement('DIV');
        
        textDiv.className = "Bold";
        textDiv.style.margin = "5px";
        textDiv.style.marginLeft = "25px";
        textDiv.innerHTML = content;
        
        var closeTd = document.createElement('TD');
        closeTd.vAlign = "top";
        
        var link = document.createElement('A');
        
        link.href = "javascript:;";
        
        var img = document.createElement('IMG');
        
        img.src = sjcl.path.mapThemeNeutralImage('tab_close.png');
        img.id = "PopupNoteCloseBtn";
        img.onclick = function()
        {
            $('PopupNote').className = "None";
            var wr = new sjcl.net.WebRequest
            (
                "../../lib/ajax/PopupNotes.php?read=1&userId=" + userId + "&noteId=" + noteId,
                function()
                {
                    return;
                },
                null,
                "POST",
                ""
            );
        };
        var onImgOver = function(){this.src = sjcl.path.mapThemeNeutralImage('tab_close_hover.png');};
        var onImgOut = function(){this.src = sjcl.path.mapThemeNeutralImage('tab_close.png');};
        sjcl.event.addMouseHoverEvents(img, onImgOver.bind(img), onImgOut.bind(img));
        
        link.appendChild(img);
        closeTd.appendChild(link);
        textTd.appendChild(textDiv);
        tr.appendChild(textTd);
        tr.appendChild(closeTd);
        innerTbody.appendChild(tr);
        innerTable.appendChild(innerTbody);
        mainDiv.appendChild(innerTable);
        
        $('PageHeader').parentNode.appendChild(mainDiv);
        
        adjustBodyHeight();
    }
}

var g_UserProfile = new UserProfile();
var g_PageBar = new PageBar();

//g_HotKeys.register(gotoTSItem, 71, true);				//Ctrl+G
//g_HotKeys.register(quickFind, 114, true);				//Ctrl+F3
//g_HotKeys.register(tsSearch, 83, true, false, true);	//Ctrl+Shift+S
g_HotKeys.register(findAccount, 85, true);				//Ctrl+U
g_HotKeys.register(addToGoUrls, 71, false, true);		//ALT+G

sjcl.event.add(window, "load",
	function()
	{
		adjustBodyHeight();
		g_PageBar.attach($("PageBar"));
	}
);

//window.setInterval(function(){window.status = g_WinManager.windows.length();}, "1000");

