var maxBannerHeight = 200;//305;
var minBannerHeight = 200;//160;
function changeElementHeight(toHeight, elementToResize, freq, delta){
    var speed = delta;
    var direction;
    if (elementToResize.offsetHeight >= toHeight){
        direction = -1;
    }else{
        direction = 1;
    }

    var intervalId = setInterval(function(){
        
        var currentHeight = elementToResize.offsetHeight;
        speed*=1.1;
        var newHeight = currentHeight + (speed * direction);
        if (elementToResize.id == 'bannerContainerSwfContainer')
        {
            var headerMainBlock = document.getElementById('headerMainBlock');
            var currentHeaderMainBlockHeight = headerMainBlock.offsetHeight;
            var newHeaderMainBlockHeight = currentHeaderMainBlockHeight + (speed * direction);
        }

        if  (
            ((direction == 1) && (newHeight + (speed * direction) >= toHeight)) ||
            ((direction == -1) && (newHeight + (speed * direction) <= toHeight)) ||
            (currentHeight == newHeight)
            )
        {
            elementToResize.style.height = toHeight + 'px';
            if (elementToResize.id == 'bannerContainerSwfContainer')
            {
                headerMainBlock.style.height = toHeight + 135 + 'px';
            }
            clearInterval(intervalId);
            return true;
        }
        elementToResize.style.height = newHeight + 'px';
        if (elementToResize.id == 'bannerContainerSwfContainer')
        {
            headerMainBlock.style.height = newHeaderMainBlockHeight + 'px';
        }


    }, freq);
}

function changeBannerHeight(height){
    if (height == maxBannerHeight){
	unCollapseBanner();
    }

    if (height == minBannerHeight){
	collapseBanner();
    }
}

function unCollapseBanner(){
    var nextYear = new Date();
    nextYear.setFullYear(nextYear.getFullYear() + 1);
    //alert(document.cookie);
    document.cookie = 'bbdoBannerStateCollapsed=false; expires=' + nextYear.toGMTString() + '; path=/';
    changeElementHeight(maxBannerHeight, document.getElementById('bannerContainerSwfContainer'), 5, 20);
    //alert(document.cookie);
}

function collapseBanner(){
    var nextYear = new Date();
    nextYear.setFullYear(nextYear.getFullYear() + 1);
    //alert(document.cookie);
    document.cookie = 'bbdoBannerStateCollapsed=true; expires=' + nextYear.toGMTString() + '; path=/';
    changeElementHeight(minBannerHeight, document.getElementById('bannerContainerSwfContainer'), 5, 20);
    //alert(document.cookie);
}

/**
* DD_belatedPNG: Adds IE6 support: PNG images for CSS background-image and HTML <IMG/>.
* Author: Drew Diller
* Email: drew.diller@gmail.com
* URL: http://www.dillerdesign.com/experiment/DD_belatedPNG/
* Version: 0.0.7a
* Licensed under the MIT License: http://dillerdesign.com/experiment/DD_belatedPNG/#license
*
* Example usage:
* DD_belatedPNG.fix('.png_bg'); // argument is a CSS selector
* DD_belatedPNG.fixPng( someNode ); // argument is an HTMLDomElement
**/

/*
PLEASE READ:
Absolutely everything in this script is SILLY.  I know this.  IE's rendering of certain pixels doesn't make sense, so neither does this code!
*/

var DD_belatedPNG = {

	ns: 'DD_belatedPNG',
	imgSize: {},
	
	createVmlNameSpace: function() { /* enable VML */
		if (document.namespaces && !document.namespaces[this.ns]) {
		  document.namespaces.add(this.ns, 'urn:schemas-microsoft-com:vml');
		}
		if (window.attachEvent) {
			window.attachEvent('onbeforeunload', function() {
				DD_belatedPNG = null;
			});
		}
	},
	
	createVmlStyleSheet: function() { /* style VML, enable behaviors */
		/*
			Just in case lots of other developers have added
			lots of other stylesheets using document.createStyleSheet
			and hit the 31-limit mark, let's not use that method!
			further reading: http://msdn.microsoft.com/en-us/library/ms531194(VS.85).aspx
		*/
		var style = document.createElement('style');
		document.documentElement.firstChild.insertBefore(style, document.documentElement.firstChild.firstChild);
		var styleSheet = style.styleSheet;
		styleSheet.addRule(this.ns + '\\:*', '{behavior:url(#default#VML)}');
		styleSheet.addRule(this.ns + '\\:shape', 'position:absolute;');
		styleSheet.addRule('img.' + this.ns + '_sizeFinder', 'behavior:none; border:none; position:absolute; z-index:-1; top:-10000px; visibility:hidden;'); /* large negative top value for avoiding vertical scrollbars for large images, suggested by James O'Brien, http://www.thanatopsic.org/hendrik/ */
		this.styleSheet = styleSheet;
	},
	
	readPropertyChange: function() {
		var el = event.srcElement;
		if (event.propertyName.search('background') != -1 || event.propertyName.search('border') != -1) {
			DD_belatedPNG.applyVML(el);
		}
		if (event.propertyName == 'style.display') {
			var display = (el.currentStyle.display == 'none') ? 'none' : 'block';
			for (var v in el.vml) {
				el.vml[v].shape.style.display = display;
			}
		}
		if (event.propertyName.search('filter') != -1) {
			DD_belatedPNG.vmlOpacity(el);
		}
	},
	
	vmlOpacity: function(el) {
		if (el.currentStyle.filter.search('lpha') != -1) {
			var trans = el.currentStyle.filter;
			trans = parseInt(trans.substring(trans.lastIndexOf('=')+1, trans.lastIndexOf(')')), 10)/100;
			el.vml.color.shape.style.filter = el.currentStyle.filter; /* complete guesswork */
			el.vml.image.fill.opacity = trans; /* complete guesswork */
		}
	},
	
	handlePseudoHover: function(el) {
		setTimeout(function() { /* wouldn't work as intended without setTimeout */
			DD_belatedPNG.applyVML(el);
		}, 1);
	},
	
	/**
	* This is the method to use in a document.
	* @param {String} selector - REQUIRED - a CSS selector, such as '#doc .container'
	**/
	fix: function(selector) {
		var selectors = selector.split(','); /* multiple selectors supported, no need for multiple calls to this anymore */
		for (var i=0; i<selectors.length; i++) {
			this.styleSheet.addRule(selectors[i], 'behavior:expression(DD_belatedPNG.fixPng(this))'); /* seems to execute the function without adding it to the stylesheet - interesting... */
		}
	},
	
	applyVML: function(el) {
		el.runtimeStyle.cssText = '';
		this.vmlFill(el);
		this.vmlOffsets(el);
		this.vmlOpacity(el);
		if (el.isImg) {
			this.copyImageBorders(el);
		}
	},
	
	attachHandlers: function(el) {
		var self = this;
		var handlers = {resize: 'vmlOffsets', move: 'vmlOffsets'};
		if (el.nodeName == 'A') {
			var moreForAs = {mouseleave: 'handlePseudoHover', mouseenter: 'handlePseudoHover', focus: 'handlePseudoHover', blur: 'handlePseudoHover'};
			for (var a in moreForAs) {
				handlers[a] = moreForAs[a];
			}
		}
		for (var h in handlers) {
			el.attachEvent('on' + h, function() {
				self[handlers[h]](el);
			});
		}
		el.attachEvent('onpropertychange', this.readPropertyChange);
	},
	
	giveLayout: function(el) {
		el.style.zoom = 1;
		if (el.currentStyle.position == 'static') {
			el.style.position = 'relative';
		}
	},
	
	copyImageBorders: function(el) {
		var styles = {'borderStyle':true, 'borderWidth':true, 'borderColor':true};
		for (var s in styles) {
			el.vml.color.shape.style[s] = el.currentStyle[s];
		}
	},
	
	vmlFill: function(el) {
		if (!el.currentStyle) {
			return;
		} else {
			var elStyle = el.currentStyle;
		}
		for (var v in el.vml) {
			el.vml[v].shape.style.zIndex = elStyle.zIndex;
		}
		el.runtimeStyle.backgroundColor = '';
		el.runtimeStyle.backgroundImage = '';
		var noColor = (elStyle.backgroundColor == 'transparent');
		var noImg = true;
		if (elStyle.backgroundImage != 'none' || el.isImg) {
			if (!el.isImg) {
				el.vmlBg = elStyle.backgroundImage;
				el.vmlBg = el.vmlBg.substr(5, el.vmlBg.lastIndexOf('")')-5);
			}
			else {
				el.vmlBg = el.src;
			}
			var lib = this;
			if (!lib.imgSize[el.vmlBg]) { /* determine size of loaded image */
				var img = document.createElement('img');
				lib.imgSize[el.vmlBg] = img;
				img.className = lib.ns + '_sizeFinder';
				img.runtimeStyle.cssText = 'behavior:none; position:absolute; left:-10000px; top:-10000px; border:none;'; /* make sure to set behavior to none to prevent accidental matching of the helper elements! */
				img.attachEvent('onload', function() {
					this.width = this.offsetWidth; /* weird cache-busting requirement! */
					this.height = this.offsetHeight;
					lib.vmlOffsets(el);
				});
				img.src = el.vmlBg;
				img.removeAttribute('width');
				img.removeAttribute('height');
				document.body.insertBefore(img, document.body.firstChild);
			}
			el.vml.image.fill.src = el.vmlBg;
			noImg = false;
		}
		el.vml.image.fill.on = !noImg;
		el.vml.image.fill.color = 'none';
		el.vml.color.shape.style.backgroundColor = elStyle.backgroundColor;
		el.runtimeStyle.backgroundImage = 'none';
		el.runtimeStyle.backgroundColor = 'transparent';
	},
	
	/* IE can't figure out what do when the offsetLeft and the clientLeft add up to 1, and the VML ends up getting fuzzy... so we have to push/enlarge things by 1 pixel and then clip off the excess */
	vmlOffsets: function(el) {
		var thisStyle = el.currentStyle;
		var size = {'W':el.clientWidth+1, 'H':el.clientHeight+1, 'w':this.imgSize[el.vmlBg].width, 'h':this.imgSize[el.vmlBg].height, 'L':el.offsetLeft, 'T':el.offsetTop, 'bLW':el.clientLeft, 'bTW':el.clientTop};
		var fudge = (size.L + size.bLW == 1) ? 1 : 0;
		
		/* vml shape, left, top, width, height, origin */
		var makeVisible = function(vml, l, t, w, h, o) {
			vml.coordsize = w+','+h;
			vml.coordorigin = o+','+o;
			vml.path = 'm0,0l'+w+',0l'+w+','+h+'l0,'+h+' xe';
			vml.style.width = w + 'px';
			vml.style.height = h + 'px';
			vml.style.left = l + 'px';
			vml.style.top = t + 'px';
		};
		makeVisible(el.vml.color.shape, (size.L + (el.isImg ? 0 : size.bLW)), (size.T + (el.isImg ? 0 : size.bTW)), (size.W-1), (size.H-1), 0);
		makeVisible(el.vml.image.shape, (size.L + size.bLW), (size.T + size.bTW), (size.W), (size.H), 1);
		
		var bg = {'X':0, 'Y':0};
		var figurePercentage = function(axis, position) {
			var fraction = true;
			switch(position) {
				case 'left':
				case 'top':
					bg[axis] = 0;
					break;
				case 'center':
					bg[axis] = .5;
					break;
				case 'right':
				case 'bottom':
					bg[axis] = 1;
					break;
				default:
					if (position.search('%') != -1) {
						bg[axis] = parseInt(position)*.01;
					}
					else {
						fraction = false;
					}
			}
			var horz = (axis == 'X');
			bg[axis] = Math.ceil(fraction ? ( (size[horz?'W': 'H'] * bg[axis]) - (size[horz?'w': 'h'] * bg[axis]) ) : parseInt(position));
			if (bg[axis] == 0) {
				bg[axis]++;
			}
		};
		for (var b in bg) {
			figurePercentage(b, thisStyle['backgroundPosition'+b]);
		}
		
		el.vml.image.fill.position = (bg.X/size.W) + ',' + (bg.Y/size.H);
		
		var bgR = thisStyle.backgroundRepeat;
		var dC = {'T':1, 'R':size.W+fudge, 'B':size.H, 'L':1+fudge}; /* these are defaults for repeat of any kind */
		var altC = { 'X': {'b1': 'L', 'b2': 'R', 'd': 'W'}, 'Y': {'b1': 'T', 'b2': 'B', 'd': 'H'} };
		if (bgR != 'repeat') {
			var c = {'T':(bg.Y), 'R':(bg.X+size.w), 'B':(bg.Y+size.h), 'L':(bg.X)}; /* these are defaults for no-repeat - clips down to the image location */
			if (bgR.search('repeat-') != -1) { /* now let's revert to dC for repeat-x or repeat-y */
				var v = bgR.split('repeat-')[1].toUpperCase();
				c[altC[v].b1] = 1;
				c[altC[v].b2] = size[altC[v].d];
			}
			if (c.B > size.H) {
				c.B = size.H;
			}
			el.vml.image.shape.style.clip = 'rect('+c.T+'px '+(c.R+fudge)+'px '+c.B+'px '+(c.L+fudge)+'px)';
		}
		else {
			el.vml.image.shape.style.clip = 'rect('+dC.T+'px '+dC.R+'px '+dC.B+'px '+dC.L+'px)';
		}
	},
	
	fixPng: function(el) {
		el.style.behavior = 'none';
		if (el.nodeName == 'BODY' || el.nodeName == 'TD' || el.nodeName == 'TR') { /* elements not supported yet */
			return;
		}
		el.isImg = false;
		if (el.nodeName == 'IMG') {
			if(el.src.toLowerCase().search(/\.png$/) != -1) {
				el.isImg = true;
				el.style.visibility = 'hidden';
			}
			else {
				return;
			}
		}
		else if (el.currentStyle.backgroundImage.toLowerCase().search('.png') == -1) {
			return;
		}
		var lib = DD_belatedPNG;
		el.vml = {color: {}, image: {}};
		var els = {shape: {}, fill: {}};
		for (var r in el.vml) {
			for (var e in els) {
				var nodeStr = lib.ns + ':' + e;
				el.vml[r][e] = document.createElement(nodeStr);
			}
			el.vml[r].shape.stroked = false;
			el.vml[r].shape.appendChild(el.vml[r].fill);
			el.parentNode.insertBefore(el.vml[r].shape, el);
		}
		el.vml.image.shape.fillcolor = 'none'; /* Don't show blank white shapeangle when waiting for image to load. */
		el.vml.image.fill.type = 'tile'; /* Ze magic!! Makes image show up. */
		el.vml.color.fill.on = false; /* Actually going to apply vml element's style.backgroundColor, so hide the whiteness. */
		
		lib.attachHandlers(el);
		
		lib.giveLayout(el);
		lib.giveLayout(el.offsetParent);
		
		/* set up element */
		lib.applyVML(el);
	}
	
};

/*
 * runOnLoad.js: portable registration for onload event handlers.
 * 
 * This module defines a single runOnLoad() function for portably registering
 * functions that can be safely invoked only when the document is fully loaded
 * and the DOM is available.
 *
 * Functions registered with runOnLoad() will not be passed any arguments when
 * invoked. They will not be invoked as a method of any meaningful object, and
 * the this keyword should not be used.  Functions registered with runOnLoad()
 * will be invoked in the order in which they were registered.  There is no
 * way to deregister a function once it has been passed to runOnLoad().
 *
 * In old browsers that do not support addEventListener() or attachEvent(),
 * this function relies on the DOM Level 0 window.onload property and will not
 * work correctly when used in documents that set the onload attribute
 * of their <body> or <frameset> tags.
 */
function runOnLoad(f) {
    if (runOnLoad.loaded) f();    // If already loaded, just invoke f() now.
    else runOnLoad.funcs.push(f); // Otherwise, store it for later
}

runOnLoad.funcs = []; // The array of functions to call when the document loads
runOnLoad.loaded = false; // The functions have not been run yet.

// Run all registered functions in the order in which they were registered.
// It is safe to call runOnLoad.run() more than once: invocations after the
// first do nothing. It is safe for an initialization function to call
// runOnLoad() to register another function.
runOnLoad.run = function() {
    if (runOnLoad.loaded) return;  // If we've already run, do nothing

    for(var i = 0; i < runOnLoad.funcs.length; i++) {
        try { runOnLoad.funcs[i](); }
        catch(e) { /* An exception in one function shouldn't stop the rest */ }
    }
    
    runOnLoad.loaded = true; // Remember that we've already run once.
    delete runOnLoad.funcs;  // But don't remember the functions themselves.
    delete runOnLoad.run;    // And forget about this function too!
};

// Register runOnLoad.run() as the onload event handler for the window
if (window.addEventListener)
    window.addEventListener("load", runOnLoad.run, false);
else if (window.attachEvent) window.attachEvent("onload", runOnLoad.run);
else window.onload = runOnLoad.run;



/**
 * browser.js: a simple client sniffer
 * 
 * This module defines an object named "browser" that is easier to use than
 * the "navigator" object.
 */
var browser = {
    version: parseInt(navigator.appVersion),
    isNetscape: navigator.appName.indexOf("Netscape") != -1, 
    isMicrosoft: navigator.appName.indexOf("Microsoft") != -1,
    isIE6: ((navigator.userAgent.indexOf("MSIE 6.0") != -1)),
    isIE8: ((navigator.userAgent.indexOf("MSIE 8.0") != -1))
};

/* *** */

function fixIE6PNG(){
    try {
	document.execCommand("BackgroundImageCache", false, true); /* TredoSoft Multiple IE doesn't like this, so try{} it */
    } catch(r) {}
    DD_belatedPNG.createVmlNameSpace();
    DD_belatedPNG.createVmlStyleSheet();
    //alert('DD_belated loaded');
    DD_belatedPNG.fix('.digestItemSticker');
}

function ShowElement(elementToShow){
    if (!elementToShow.abortHiding){
	elementToShow.abortHiding = true;
    }
    
    elementToShow.style.display = 'block';
}

function HideElementDelayed(elementToHide){
    elementToHide.abortHiding = false;
    var HideElement = function() {
				    if(!elementToHide.abortHiding){
					elementToHide.style.display = 'none'
				    }
				};
    setTimeout(HideElement, 400);
}

function GetNextIllustrationId(currentId){

    for (var illustrIndex = 0; illustrIndex < illustrationsInfo.length; illustrIndex++){
	if (illustrationsInfo[illustrIndex].id == currentId){
	    if(illustrationsInfo[illustrIndex + 1]){
		return illustrationsInfo[illustrIndex + 1].id;
	    }else{
		return illustrationsInfo[0].id;
	    }
	}
    }
}

function GetPrevllustrationId(currentId){

    for (var illustrIndex = 0; illustrIndex < illustrationsInfo.length; illustrIndex++){
	if (illustrationsInfo[illustrIndex].id == currentId){
	    if(illustrationsInfo[illustrIndex - 1]){
		return illustrationsInfo[illustrIndex - 1].id;
	    }else{
		return illustrationsInfo[illustrationsInfo.length - 1].id;
	    }
	}
    }
}

function ShowNextIllustration(){
    var nextId = GetNextIllustrationId(activeIllustrationId);
    ShowIllustration(nextId);
}

function ShowPrevIllustration(){
    var nextId = GetPrevllustrationId(activeIllustrationId);
    ShowIllustration(nextId);
}

function GetIllustrationByIdFromArray(findId){
    for (var illustrIndex = 0; illustrIndex < illustrationsInfo.length; illustrIndex++){
	if (illustrationsInfo[illustrIndex].id == findId){
	    return illustrationsInfo[illustrIndex];
	}
    }
    return false;
}

function GetIllustrationNumberByIdFromArray(findId){
    for (var illustrIndex = 0; illustrIndex < illustrationsInfo.length; illustrIndex++){
	if (illustrationsInfo[illustrIndex].id == findId){
	    return illustrIndex + 1;
	}
    }
    return false;
}

function ShowIllustrationHandler(illustrationId){
    ShowIllustration(illustrationId);
}

function ShowIllustration(id){
    var thumbsContainers = document.getElementById('illustrationsThumbsBlock').getElementsByTagName('div');
    ResetAllActiveIllustrThumbs(thumbsContainers);
    HighlightThumbContainer(document.getElementById('illustrThumbContainer_' + id));
    
    var illustrationContainer = document.getElementById('illustrationContainer');
    
    if (illustrationContainer.hasChildNodes()){
	while(illustrationContainer.childNodes.length >= 1){
	    illustrationContainer.removeChild(illustrationContainer.firstChild);
	} 
    }
    
    if(GetIllustrationByIdFromArray(id).mediaType == 'image'){
	illustrationContainer.innerHTML = '<img src="' + GetIllustrationByIdFromArray(id).bigImagePath + '" alt=""/>';
    }
    
    if(GetIllustrationByIdFromArray(id).mediaType == 'video'){
	illustrationContainer.innerHTML = '&nbsp;<!--ie6 trick -->' + GetIllustrationByIdFromArray(id).videoHtml;
    }
    
    if(GetIllustrationByIdFromArray(id).description == null){
	document.getElementById('illustrationDescriptionContainer').innerHTML = '';
    }else{
	document.getElementById('illustrationDescriptionContainer').innerHTML = GetIllustrationByIdFromArray(id).description;
    }
    
    document.getElementById('currentAndTotalInfoSpan').innerHTML = GetIllustrationNumberByIdFromArray(id) + '/' + illustrationsInfo.length;
    activeIllustrationId = id;
}

function HighlightThumbContainer(thumbContatiner){
    if (thumbContatiner.className == 'illustrationsThumbContainerStd'){
	thumbContatiner.className = 'illustrationsThumbContainerActive';
    }
}

function ResetAllActiveIllustrThumbs(thumbContainers){
    for (var currThumbContainerIndex = 0; currThumbContainerIndex < thumbContainers.length; currThumbContainerIndex++){
	if (thumbContainers[currThumbContainerIndex].className == 'illustrationsThumbContainerActive'){
	    thumbContainers[currThumbContainerIndex].className = 'illustrationsThumbContainerStd';
	}
    }
}

function showLecturesByCourse(){
    var courseName = document.getElementById('filterSelect').value;
    window.location = '/lectures/list/' + courseName;
}

function showNewsByCourse(){
    var courseName = document.getElementById('filterSelect').value;
    window.location = '/news/list/' + courseName;
}

function showWorksByCourse(){
    var courseName = document.getElementById('filterSelect').value;
    window.location = '/works/list/' + courseName;
}

function showPeoplesByCourse(roleInUrl, viewMode){
    var courseName = document.getElementById('filterSelect').value;
    window.location = '/peoples/' + roleInUrl + '/' + viewMode + '/' + courseName;
}

var courseShortDescrViewer = new Object();
courseShortDescrViewer.currentUncollapsedBlock = null;
courseShortDescrViewer.currentUncollapsedBlockLink = null;
courseShortDescrViewer.showOrHideShortDescr = function(clickedLinkElement){
	
    var courseContainer = clickedLinkElement.parentNode.parentNode
    var currentNode;
    var descrInner;
    for (var currentNodeIndex = 0; currentNodeIndex < courseContainer.childNodes.length; currentNodeIndex++){
		currentNode = courseContainer.childNodes[currentNodeIndex];
		if((currentNode.nodeType == 1) && (currentNode.className == 'collapsedBlockWrp')){
			var descrWrp = currentNode;
			var descrInner = currentNode.getElementsByTagName('div')[0];
		}
    }
	
    if (clickedLinkElement.collapsed == true){
		this.collapseShorDescr(descrWrp, descrInner, clickedLinkElement);
		clickedLinkElement.collapsed = false;
	}else{
		this.uncollapseShorDescr(descrWrp, descrInner, clickedLinkElement);
		clickedLinkElement.collapsed = true;
	}
}

courseShortDescrViewer.collapseShorDescr = function(descrWrp, descrInner, clickedLinkElement){
	changeElementHeight(0, descrWrp, 10, 20);
}

courseShortDescrViewer.uncollapseShorDescr = function(descrWrp, descrInner, clickedLinkElement){
    innerCollapsedBlockFullHeight = 30 + descrInner.offsetHeight; /* 30 magic number is sum of vertical margins, which are absents in offsetHeight */
    changeElementHeight(innerCollapsedBlockFullHeight, descrWrp, 10, 20);
}




runOnLoad(function(){
    if (browser.isIE6){
	fixIE6PNG();
    }
    
    if (!(window.console && window.console.firebug)){
	console = new Object();
	console.log = function(){};
    }

    var peoplesMenuItem = document.getElementById("peoplesMenuItem");
    var peoplesSubmenuContainer = document.getElementById("peoplesSubmenuContainer");

    peoplesMenuItem.onmouseover = function() {ShowElement(peoplesSubmenuContainer)};
    peoplesMenuItem.onmouseout = function() {HideElementDelayed(peoplesSubmenuContainer)};
    peoplesSubmenuContainer.onmouseover = function() {ShowElement(peoplesSubmenuContainer)};
    peoplesSubmenuContainer.onmouseout = function() {HideElementDelayed(peoplesSubmenuContainer)};
    
});


function digestMoreItemsRetreiverActivate(){
    buttonObj = document.getElementById('digestMoreRetreiverLink');
    buttonObj.className = 'readyState';
    buttonObj.onclick = function(){ return getAdditionalDigetItems() };
}

function digestMoreItemsRetreiverDeactivate(){
    buttonObj = document.getElementById('digestMoreRetreiverLink');
    buttonObj.onclick = function() {return false;};
    buttonObj.className = "busyState";
}

function digestMoreItemsRetreiverHide(){
    buttonObj = document.getElementById('digestMoreRetreiverLink');
    buttonObj.style.display = 'none';
}

var putIntoColNum = null;

var appendDigestAjaxDataArrivedHandler = function(additionalDigestItemsInJson){
    if (putIntoColNum == null){
	putIntoColNum = clientDigestInitSettings.continueLoadingStratingFromCol;
    }
    
    var responseArray = JSON.parse(additionalDigestItemsInJson);
    if (responseArray){
	digestItemsEndReached = !responseArray.hasMoreItems;
	var newItems = responseArray.items;
	var cols = getDigestThreeCols();
	
	for (var newItemIdx = 0; newItemIdx < newItems.length; newItemIdx++){
	    //console.log('putting in col ' + putIntoColNum);
	    putNewDigestItemIntoCol(cols[putIntoColNum], newItems[newItemIdx]);
	    if (putIntoColNum++ == 2){
		putIntoColNum = 0;
	    }
	}
	digestNextBlockToGet++;
    }
    
    digestMoreItemsRetreiverActivate();
    
    if (digestItemsEndReached){
	digestMoreItemsRetreiverHide();
    }
};

function putNewDigestItemIntoCol(columnObj, digestItemObj){
    var urlLinkToItem = digestItemObj.type + '/' + digestItemObj.__urlName;
    var urlLinkToCourse = '/courses/' + digestItemObj.course.Course_urlName;
    var urlLinkToListByCourse = digestItemObj.type + '/list/' + digestItemObj.course.Course_urlName;
    
    var digestItemDomDiv = document.createElement('div');
    digestItemDomDiv.className = 'digestItem';
    
    var digestItemPicOrQuoteCntnrDomDiv = document.createElement('div');
    digestItemPicOrQuoteCntnrDomDiv.className = 'digestItemPicOrQuoteCntnr';
    
    var linkAtIllustrationDomA = document.createElement('a');
    linkAtIllustrationDomA.href = urlLinkToItem;
    
    //on image
    if(digestItemObj.illustration.Illustration_mediaType == 'image'){
	var illustrationImageDomImg = document.createElement('img');
	illustrationImageDomImg.src = digestItemObj.illustration.Illustration_digestImagePath;
	linkAtIllustrationDomA.appendChild(illustrationImageDomImg);
	digestItemPicOrQuoteCntnrDomDiv.appendChild(linkAtIllustrationDomA);
    }
    if(digestItemObj.illustration.Illustration_mediaType == 'quotation'){
	var illustrationQuotationDomDiv = document.createElement('div');
	illustrationQuotationDomDiv.className = 'qoutationIllustration';
	
	var illustrationTextLinkDomA = document.createElement('a');
	illustrationTextLinkDomA.href = urlLinkToItem;
	//illustrationTextLinkDomA.appendChild(document.createTextNode(digestItemObj.illustration.Illustration_quotationText));
	illustrationTextLinkDomA.innerHTML = digestItemObj.illustration.Illustration_quotationText;
	illustrationQuotationDomDiv.appendChild(illustrationTextLinkDomA);
	digestItemPicOrQuoteCntnrDomDiv.appendChild(illustrationQuotationDomDiv);
    }
    
    digestItemPicOrQuoteCntnrDomDiv.appendChild(linkAtIllustrationDomA);
    digestItemDomDiv.appendChild(digestItemPicOrQuoteCntnrDomDiv);
    
    var ie6StrangeBugFixWrapperDomDiv = document.createElement('div');
    ie6StrangeBugFixWrapperDomDiv.className = 'ie6StrangeBugFixWrapper';
    
    var digestItemRubricDomA1 = document.createElement('a');
    //digestItemRubricDomA1.appendChild(document.createTextNode(digestItemObj.course.Course_name));
    digestItemRubricDomA1.innerHTML = digestItemObj.course.Course_name;
    digestItemRubricDomA1.href = urlLinkToCourse;
    digestItemRubricDomA1.className = 'digestItemRubric';
    
    var digestItemTitleArrowDomImg1 = document.createElement('img');
    digestItemTitleArrowDomImg1.className = 'digestItemTitleArrow';
    digestItemTitleArrowDomImg1.src = '/resources/images/digest_arrow.png';
    
    var digestItemRubricDomA2 = document.createElement('a');
    digestItemRubricDomA2.appendChild(document.createTextNode(digestItemObj.catRuName));
    digestItemRubricDomA2.className = 'digestItemRubric';
    digestItemRubricDomA2.href = urlLinkToListByCourse;
    
    var digestItemTitleArrowDomImg2 = document.createElement('img');
    digestItemTitleArrowDomImg2.className = 'digestItemTitleArrow';
    digestItemTitleArrowDomImg2.src = '/resources/images/digest_arrow.png';
    
    var digestItemTitleDomA = document.createElement('a');
    digestItemTitleDomA.className = 'digestItemTitle';
    digestItemTitleDomA.href = urlLinkToItem;
    //digestItemTitleDomA.appendChild(document.createTextNode(digestItemObj.__name));
    digestItemTitleDomA.innerHTML = digestItemObj.__name;
    
    var digestItemTextDomP  = document.createElement('p');
    digestItemTextDomP.className = 'digestItemText';
    //digestItemTextDomP.appendChild(document.createTextNode(digestItemObj.__shortText));
    
    if(digestItemObj.__shortText != null){
	digestItemTextDomP.innerHTML = digestItemObj.__shortText;
    }
    
    var digestItemDateDomP = document.createElement('p');
    digestItemDateDomP.className = 'digestItemDate';
    digestItemDateDomP.appendChild(document.createTextNode(digestItemObj.date));
    
    ie6StrangeBugFixWrapperDomDiv.appendChild(digestItemRubricDomA1);
    ie6StrangeBugFixWrapperDomDiv.appendChild(digestItemTitleArrowDomImg1);
    ie6StrangeBugFixWrapperDomDiv.appendChild(digestItemRubricDomA2);
    ie6StrangeBugFixWrapperDomDiv.appendChild(digestItemTitleArrowDomImg2);
    ie6StrangeBugFixWrapperDomDiv.appendChild(digestItemTitleDomA);
	if(digestItemTextDomP.innerHTML){
		ie6StrangeBugFixWrapperDomDiv.appendChild(digestItemTextDomP);
	}
	ie6StrangeBugFixWrapperDomDiv.appendChild(digestItemDateDomP);
    
    digestItemDomDiv.appendChild(ie6StrangeBugFixWrapperDomDiv);
    /*
	<a class="digestItemRubric" href="/courses/Wordshop5">Wordshop 5</a>
	<img class="digestItemTitleArrow" src="/resources/images/digest_arrow.png" alt=""/>
	<a class="digestItemRubric" href="lectures/list/Wordshop5">������</a>
	<img class="digestItemTitleArrow" src="/resources/images/digest_arrow.png" alt=""/>
	<a class="digestItemTitle" href="/lectures/MetodikiRabotiNadNazvaniami"> �������� ������ ��� ���������� </a>
	<p class="digestItemText">����� ������� ��� �������, � ����� ������, ��������� �� ����� �����, � ����������� ������� ��������� ������������ ��������, ������� ����� ���������� �� ����������������, �������� ����� �����������, ������������ �� ������������ � �������, �������� �������� �����������, ��� ���� �� ����������� ��������� ������� ���� ������.</p>
	<p class="digestItemDate">19.04.2009</p>
    */
    columnObj.appendChild(digestItemDomDiv);
}

var digestNextBlockToGet = null; //clientDigestInitSettings;
var digestItemsEndReached = false;

function getAdditionalDigetItems(){
    if (!digestItemsEndReached){
	
	if (!digestNextBlockToGet){
	    digestNextBlockToGet = clientDigestInitSettings.initiallyDisplayedBlocks;
	}
	
	digestMoreItemsRetreiverDeactivate();
	
	HTTP.getText('/digest/AjaxGetRange/' + digestNextBlockToGet, appendDigestAjaxDataArrivedHandler);
    }
    return false;
}

function getDigestThreeCols(){
    var chNodes = document.getElementById('contentBlock').childNodes;
    var cols = [], currentFoundCol = 0;
    for(var childIdx = 0; childIdx < chNodes.length; childIdx++){
	if (	(chNodes[childIdx].className == 'digestCol') ||
		(chNodes[childIdx].className == 'digestCenterCol') ){
	    cols[currentFoundCol++] = chNodes[childIdx];
	}
    }
    return (cols);
}

/* http */
var HTTP = {};
// This is a list of XMLHttpRequest creation factory functions to try
HTTP._factories = [
    function() { return new XMLHttpRequest(); },
    function() { return new ActiveXObject("Msxml2.XMLHTTP"); },
    function() { return new ActiveXObject("Microsoft.XMLHTTP"); }
];

// When we find a factory that works, store it here
HTTP._factory = null;

// Create and return a new XMLHttpRequest object.
// 
// The first time we're called, try the list of factory functions until
// we find one that returns a nonnull value and does not throw an
// exception.  Once we find a working factory, remember it for later use.
//
HTTP.newRequest = function() {
    if (HTTP._factory != null) return HTTP._factory();

    for(var i = 0; i < HTTP._factories.length; i++) {
        try {
            var factory = HTTP._factories[i];
            var request = factory();
            if (request != null) {
                HTTP._factory = factory;
                return request;
            }
        }
        catch(e) {
            continue;
        }
    }

    // If we get here, none of the factory candidates succeeded,
    // so throw an exception now and for all future calls.
    HTTP._factory = function() {
        throw new Error("XMLHttpRequest not supported");
    }
    HTTP._factory(); // Throw an error
};


HTTP.getText = function(url, callback) {
    var request = HTTP.newRequest();
    request.onreadystatechange = function() {
        if (request.readyState == 4 && request.status == 200)
            callback(request.responseText);
    }
    request.open("GET", url);
    request.send(null);
};



/*
    http://www.JSON.org/json2.js
    2009-04-16

    Public Domain.

    NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

    See http://www.JSON.org/js.html

    This file creates a global JSON object containing two methods: stringify
    and parse.

        JSON.stringify(value, replacer, space)
            value       any JavaScript value, usually an object or array.

            replacer    an optional parameter that determines how object
                        values are stringified for objects. It can be a
                        function or an array of strings.

            space       an optional parameter that specifies the indentation
                        of nested structures. If it is omitted, the text will
                        be packed without extra whitespace. If it is a number,
                        it will specify the number of spaces to indent at each
                        level. If it is a string (such as '\t' or '&nbsp;'),
                        it contains the characters used to indent at each level.

            This method produces a JSON text from a JavaScript value.

            When an object value is found, if the object contains a toJSON
            method, its toJSON method will be called and the result will be
            stringified. A toJSON method does not serialize: it returns the
            value represented by the name/value pair that should be serialized,
            or undefined if nothing should be serialized. The toJSON method
            will be passed the key associated with the value, and this will be
            bound to the object holding the key.

            For example, this would serialize Dates as ISO strings.

                Date.prototype.toJSON = function (key) {
                    function f(n) {
                        // Format integers to have at least two digits.
                        return n < 10 ? '0' + n : n;
                    }

                    return this.getUTCFullYear()   + '-' +
                         f(this.getUTCMonth() + 1) + '-' +
                         f(this.getUTCDate())      + 'T' +
                         f(this.getUTCHours())     + ':' +
                         f(this.getUTCMinutes())   + ':' +
                         f(this.getUTCSeconds())   + 'Z';
                };

            You can provide an optional replacer method. It will be passed the
            key and value of each member, with this bound to the containing
            object. The value that is returned from your method will be
            serialized. If your method returns undefined, then the member will
            be excluded from the serialization.

            If the replacer parameter is an array of strings, then it will be
            used to select the members to be serialized. It filters the results
            such that only members with keys listed in the replacer array are
            stringified.

            Values that do not have JSON representations, such as undefined or
            functions, will not be serialized. Such values in objects will be
            dropped; in arrays they will be replaced with null. You can use
            a replacer function to replace those with JSON values.
            JSON.stringify(undefined) returns undefined.

            The optional space parameter produces a stringification of the
            value that is filled with line breaks and indentation to make it
            easier to read.

            If the space parameter is a non-empty string, then that string will
            be used for indentation. If the space parameter is a number, then
            the indentation will be that many spaces.

            Example:

            text = JSON.stringify(['e', {pluribus: 'unum'}]);
            // text is '["e",{"pluribus":"unum"}]'


            text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
            // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'

            text = JSON.stringify([new Date()], function (key, value) {
                return this[key] instanceof Date ?
                    'Date(' + this[key] + ')' : value;
            });
            // text is '["Date(---current time---)"]'


        JSON.parse(text, reviver)
            This method parses a JSON text to produce an object or array.
            It can throw a SyntaxError exception.

            The optional reviver parameter is a function that can filter and
            transform the results. It receives each of the keys and values,
            and its return value is used instead of the original value.
            If it returns what it received, then the structure is not modified.
            If it returns undefined then the member is deleted.

            Example:

            // Parse the text. Values that look like ISO date strings will
            // be converted to Date objects.

            myData = JSON.parse(text, function (key, value) {
                var a;
                if (typeof value === 'string') {
                    a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
                    if (a) {
                        return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
                            +a[5], +a[6]));
                    }
                }
                return value;
            });

            myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
                var d;
                if (typeof value === 'string' &&
                        value.slice(0, 5) === 'Date(' &&
                        value.slice(-1) === ')') {
                    d = new Date(value.slice(5, -1));
                    if (d) {
                        return d;
                    }
                }
                return value;
            });


    This is a reference implementation. You are free to copy, modify, or
    redistribute.

    This code should be minified before deployment.
    See http://javascript.crockford.com/jsmin.html

    USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
    NOT CONTROL.
*/

/*jslint evil: true */

/*global JSON */

/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
    call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
    getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
    lastIndex, length, parse, prototype, push, replace, slice, stringify,
    test, toJSON, toString, valueOf
*/

// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.

if (!this.JSON) {
    JSON = {};
}
(function () {

    function f(n) {
        // Format integers to have at least two digits.
        return n < 10 ? '0' + n : n;
    }

    if (typeof Date.prototype.toJSON !== 'function') {

        Date.prototype.toJSON = function (key) {

            return this.getUTCFullYear()   + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate())      + 'T' +
                 f(this.getUTCHours())     + ':' +
                 f(this.getUTCMinutes())   + ':' +
                 f(this.getUTCSeconds())   + 'Z';
        };

        String.prototype.toJSON =
        Number.prototype.toJSON =
        Boolean.prototype.toJSON = function (key) {
            return this.valueOf();
        };
    }

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        rep;


    function quote(string) {

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.

        escapable.lastIndex = 0;
        return escapable.test(string) ?
            '"' + string.replace(escapable, function (a) {
                var c = meta[a];
                return typeof c === 'string' ? c :
                    '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }) + '"' :
            '"' + string + '"';
    }


    function str(key, holder) {

// Produce a string from holder[key].

        var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];

// If the value has a toJSON method, call it to obtain a replacement value.

        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }

// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.

        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }

// What happens next depends on the value's type.

        switch (typeof value) {
        case 'string':
            return quote(value);

        case 'number':

// JSON numbers must be finite. Encode non-finite numbers as null.

            return isFinite(value) ? String(value) : 'null';

        case 'boolean':
        case 'null':

// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.

            return String(value);

// If the type is 'object', we might be dealing with an object or an array or
// null.

        case 'object':

// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.

            if (!value) {
                return 'null';
            }

// Make an array to hold the partial results of stringifying this object value.

            gap += indent;
            partial = [];

// Is the value an array?

            if (Object.prototype.toString.apply(value) === '[object Array]') {

// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.

                length = value.length;
                for (i = 0; i < length; i += 1) {
                    partial[i] = str(i, value) || 'null';
                }

// Join all of the elements together, separated with commas, and wrap them in
// brackets.

                v = partial.length === 0 ? '[]' :
                    gap ? '[\n' + gap +
                            partial.join(',\n' + gap) + '\n' +
                                mind + ']' :
                          '[' + partial.join(',') + ']';
                gap = mind;
                return v;
            }

// If the replacer is an array, use it to select the members to be stringified.

            if (rep && typeof rep === 'object') {
                length = rep.length;
                for (i = 0; i < length; i += 1) {
                    k = rep[i];
                    if (typeof k === 'string') {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            } else {

// Otherwise, iterate through all of the keys in the object.

                for (k in value) {
                    if (Object.hasOwnProperty.call(value, k)) {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            }

// Join all of the member texts together, separated with commas,
// and wrap them in braces.

            v = partial.length === 0 ? '{}' :
                gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                        mind + '}' : '{' + partial.join(',') + '}';
            gap = mind;
            return v;
        }
    }

// If the JSON object does not yet have a stringify method, give it one.

    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function (value, replacer, space) {

// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.

            var i;
            gap = '';
            indent = '';

// If the space parameter is a number, make an indent string containing that
// many spaces.

            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }

// If the space parameter is a string, it will be used as the indent string.

            } else if (typeof space === 'string') {
                indent = space;
            }

// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.

            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                     typeof replacer.length !== 'number')) {
                throw new Error('JSON.stringify');
            }

// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.

            return str('', {'': value});
        };
    }


// If the JSON object does not yet have a parse method, give it one.

    if (typeof JSON.parse !== 'function') {
        JSON.parse = function (text, reviver) {

// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.

            var j;

            function walk(holder, key) {

// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.

                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }


// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.

            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }

// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.

// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

            if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

                j = eval('(' + text + ')');

// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.

                return typeof reviver === 'function' ?
                    walk({'': j}, '') : j;
            }

// If the text is not JSON parseable, then a SyntaxError is thrown.

            throw new SyntaxError('JSON.parse');
        };
    }
}());

