
//Images
var sImagesPath = "images/";
var sImageNone = sImagesPath + "dot.gif";
var sImagePlus = sImagesPath + "plus.gif";
var sImageMinus = sImagesPath + "minus.gif";

// Preload images
pCheck= new Image(16,16);
pCheck.src="images/checked.gif";
pEmpty= new Image(16,16);
pEmpty.src="images/empty.gif";

//Styles
var sNodeLoadingClass = "BeingLoadedNode";
var sNodeClass = "TreeNode";

// check if it is ie compatible?
var agt = navigator.userAgent.toLowerCase();
var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));

// Stupid IE!
var cell_display = (is_ie?'block':'');

//Timeout during which node will be loaded
var timeOut = 60000;

//Selected node
var oSelNode;

//Curent loading node. Only one node can be being loading at one moment!*/
var beingLoadedNode;

//Curent loading lesson. Only one leson can be being loading at one moment!*/
var beingLoadedLesson;

//Curent loading lessons. Only one leson can be being loading at one moment!*/
var lessTab;

//Current selected tree node
var currNode = null;

//Init data and start loading root tree
function initPage(){
	lessTab = document.getElementById("LessonsTable");
	try{
		if(!is_ie) lessTab = lessTab.getElementsByTagName("TBODY")[0];
	}catch(e){ }
	//showBeingLoadedLessons();
	loadLessons();

	oSelNode = null;
	//set beingLoadedNode to the tree container
	beingLoadedNode = document.getElementById("Tree");
	try {
	processLoading(top.sRootTree);
	}catch(e){}
}

//Load subtree into hidden frame
function processLoading(sTreeURL){
	window.tocLoader.location = sTreeURL;
	//We will cancel loading of tree if it willn't have success during timeout
	window.setTimeout("cancelLoadByTimeout('" + beingLoadedNode.id + "');", timeOut);
}

//Show hint [Loading...]
function showBeingLoadedNode(){
	var oDIV = beingLoadedNode.appendChild(document.createElement("div"));
	oDIV.className = sNodeLoadingClass;
	var oA = oDIV.appendChild(document.createElement("a"));
	oA.href = "#";
	oA.title = "Click to cancel..."
	oA.onclick = cancelLoad;
	var	oText = oA.appendChild(document.createTextNode(sCancelLoading));
}

//Hide hint [Loading...]
function hideBeingLoadedNode(){
	if (beingLoadedNode.childNodes.length>1){
		var oDIV = beingLoadedNode.childNodes[1];
		beingLoadedNode.removeChild(oDIV);
	}
}

//Cancel loading of node
function cancelLoadByTimeout(id){
	//Check if node is still  loaded
	if (beingLoadedNode!=null && beingLoadedNode.id==id){
		hideBeingLoadedNode();
		//Check whether its top container node
		if (beingLoadedNode.childNodes.length>0){
			beingLoadedNode.childNodes[0].childNodes[0].src = sImageNone;
			beingLoadedNode.childNodes[0].childNodes[0].onclick = null;
		}
		beingLoadedNode = null;
		alert("Couldn't load subtree.");
	}
}

//This function handles OnClick event on hint [Loading...]
function cancelLoad(){
	hideBeingLoadedNode();
	//Check whether its top container node
	if (beingLoadedNode.childNodes.length>0){
		beingLoadedNode.childNodes[0].childNodes[0].src = sImagePlus;
	}
	beingLoadedNode = null;
	return false;
}

function ga_send(cat, act, label) {
        pageTracker._trackEvent(cat, act, label);
}
//This function handle OnClick event on action image ([+] or [-]).
//As parameter we pass id of associated node
function actionOnClick(id){
	var oNode = document.getElementById(id);
	//If node is already expanded we collapse it
	if (oNode.getAttribute("Expanded")=="true"){
		oNode.childNodes[1].style.display = "none";
		oNode.childNodes[0].childNodes[0].src = sImagePlus;
		oNode.setAttribute ("Expanded", "false")
	}
	//If node is collapsed we expand it
	else{
		//Show minus icon
		oNode.childNodes[0].childNodes[0].src = sImageMinus;
		//If children nodes are already loaded, just expand it
		if (oNode.getAttribute("LoadedChildren")=="true"){
			oNode.childNodes[1].style.display = "block";
			oNode.setAttribute ("Expanded", "true")
		}
		 //Children nodes are not loaded yet, we need to load it
		else{
			//If the other nodes are loaded at the current time, we should stop it
			if (beingLoadedNode!=null){
				hideBeingLoadedNode();
			}
			//Set new current being loaded node
			beingLoadedNode = oNode;
			//Show loading node
			showBeingLoadedNode();
			//loading subtree
			processLoading(beingLoadedNode.getAttribute("src"));
		}
	}
}

//Build tree. This function is called from hidden frame with new downloaded data,
//which are passed in oData parameter
function buildTree(oData){
	//Check whether loading was canceled
	if (beingLoadedNode!=null){
		hideBeingLoadedNode();
		//Get list of nodes
		var oNodes = oData.nodes;
		if (oNodes.length==0){
			if (beingLoadedNode.childNodes.length>0){
				beingLoadedNode.childNodes[0].childNodes[0].src = sImageNone;
				beingLoadedNode.childNodes[0].childNodes[0].onclick = null;
			}
		}
		else{
			var oLI, oUL, oIMG, oA, oText, oNOBR, i;
			var sIcon, sName, sHref, sTarget, sSrc;
			//Create container for child nodes
			oUL = beingLoadedNode.appendChild(document.createElement("ul"));
			oUL.style.display="block";
			//Run over nodes
			for (i=0;i<oNodes.length;i++){
				//Set obligatory values
				//sIcon = oNodes[i].icon;
				sName =	oNodes[i].name;
				//Set optional values
				if (oNodes[i].href!= null){
					sHref=oNodes[i].href;
				}
				else{
					sHref="";
				}
				if (oNodes[i].target!=null){
					sTarget=oNodes[i].target;
				}
				else{
					sTarget=""
				}
				//Create node
				oLI = oUL.appendChild(document.createElement("li"));
        oLI.className="dtree";

				if(bDirection) oLI.style.marginLeft="-25px";
				else oLI.style.marginRight="-25px";

				oLI.id = 'tn' + oNodes[i].cid;

				//If src attribute is not empty, add custom attribute to the result node
				if (oNodes[i].src!=null){
					sSrc = oNodes[i].src;
				}
				else{
					sSrc = "";
				}
				oLI.setAttribute("src", sSrc);
				oNOBR = oLI.appendChild(document.createElement("span"));
				//Create action image [+], [-] [ ]
				oIMG = document.createElement("img");
				oIMG.border = 0;
				//If src attribute is not empty or amount of the child nodes is not equals zero
				if (sSrc!=""){
					//Sub nodes was not loaded and so not expanded
					oLI.setAttribute("LoadedChildren", "false");
					oLI.setAttribute("Expanded", "false");
					oIMG.src = sImagePlus;
					//Set action image event handler - dynamicaly assembly handler for
					//It should be like actionOnClick('tnXXXX')
					oIMG.onclick = new Function("actionOnClick('tn" + oNodes[i].cid + "')");
         	oIMG.style.cursor = "hand";
				}
				else{
					oIMG.src = sImageNone;
				}
				//Create icon image
				oIMG.width = 16;
				oIMG.height = 16;
        oIMG.align = "absmiddle";
				oIMG = oNOBR.appendChild(oIMG);

				//Create link
				oA = document.createElement("a");
				if (sHref!=""){
					//Combine full path from baseHref and relative path
					//If you want to use full pathes (not relative) just
					//assing to baseHref empty string
					//oA.href = oData.baseHref + sHref;
					if(!oNodes[i].cid){
						oA.href = 'javascript: new_currNode("0"); loadLessonsAll(); treePanel(0);';
					}else{
						oA.href = 'javascript: new_currNode("' + oNodes[i].cid + '"); loadLessons(' + oNodes[i].cid + '); treePanel(0);';
					}
				}
				if (sTarget!=""){
					oA.target = sTarget;
				}
				oA.title = sName;
				oA.className = "treenode";
				oA = oNOBR.appendChild(oA);
				oText = oA.appendChild(document.createTextNode(sName));
			}
			//Add custom attributes to resultNode which specifies whether node loaded children or not and
			//whether is was expanded or not
			beingLoadedNode.setAttribute("Expanded", "true");
		}
		beingLoadedNode.setAttribute("LoadedChildren", "true")
		beingLoadedNode = null;
	}
	if(tnVisible.length>0){
    if(tnVisible.length == 1) new_currNode(tnVisible.pop());
    else actionOnClick('tn' + tnVisible.pop());
	}
}

function new_currNode(id){
	if(currNode) currNode.className="dtree";
	currNode = document.getElementById('tn' + id);
	currNode.className="dtree_sel";
}

// =======================================================
//   LESSON RELATED STUFF
// =======================================================

function open_lesson(ev, pID){
	var _ID;

	if(pID != null){
		_ID=pID;
	}else{
		_ID=this.getAttribute("lessonId");
	}

  var less  = document.getElementById('less_'+_ID);
  var les01 = document.getElementById('les01_'+_ID);
  var les02 = document.getElementById('les02_'+_ID);

  try{
    if(less.getAttribute("Expanded") == "false"){
      less.setAttribute ("Expanded", "true")
      if(les01){
      	les01.style.display=cell_display;
			}
      les02.style.display=cell_display;
      less.className="selected";
      if(les02.getAttribute("loadedFiles")=="false"){
        if(beingLoadedLesson != null){
          hideBeingLoadedLesson();
          open_lesson(beingLoadedLesson.getAttribute("less_id"));
        }
        beingLoadedLesson = document.getElementById('tbl_'+_ID);
        showBeingLoadedLesson();
        processLoadingLesson(_ID);
      }
    }else{
      less.setAttribute ("Expanded", "false")
      if(les01){
      	les01.style.display="none";
			}
      les02.style.display="none";
      less.className="deactivated";
    }
  }catch(e){ }
}

//Show hint [Loading...]
function showBeingLoadedLesson(){
  var oDIV = beingLoadedLesson.appendChild(document.createElement("div"));
  oDIV.className = sNodeLoadingClass;
  var oA = oDIV.appendChild(document.createElement("a"));
  oA.href = "#";
  oA.title = "Click to cancel..."
  oA.onclick = cancelLesLoad;
  var  oText = oA.appendChild(document.createTextNode(sCancelLoading));
}

//Hide hint [Loading...]
function hideBeingLoadedLesson(){
  while(beingLoadedLesson.childNodes.length>0){
    var oDIV = beingLoadedLesson.childNodes[0];
    beingLoadedLesson.removeChild(oDIV);
  }
}

//Load subtree into hidden frame
function processLoadingLesson(sLID){
  window.lesLoader.location = sLessLoadURL + sLID;
  //We will cancel loading of tree if it willn't have success during timeout
  //window.setTimeout("cancelLesLoadByTimeout('" + beingLoadedNode.id + "');", timeOut);
}


function buildFiles(oData){
  var i, j;
  var oDIV, oIMG, oSPAN, oA;

  if (beingLoadedLesson!=null){
    hideBeingLoadedLesson();
    var _ID = beingLoadedLesson.getAttribute("less_id");
    var les02 = this.document.getElementById('les02_'+_ID);

    for (i=0;i<oData.length;i++){
      oDIV = beingLoadedLesson.appendChild(document.createElement("div"));
      oDIV.style.background = "#F7F7F7";
      oIMG = document.createElement("img");
      oIMG.hspace=4;
      oIMG.vspace=4;
      oIMG.src=oData[i].baseImage;
      oIMG.border=0;
      oIMG.align="absmiddle";
      oDIV.appendChild(oIMG);

      oSPAN = oDIV.appendChild(document.createElement("span"));
      oSPAN.className = "top-menu";
      oSPAN.appendChild(document.createTextNode(oData[i].baseName + ":"));

      for (j=0;j<oData[i].files.length;j++){
        oDIV.appendChild(document.createTextNode(" "));
        oSPAN = oDIV.appendChild(document.createElement("nobr"));
        oA = oSPAN.appendChild(document.createElement("a"));
        var href=oData[i].files[j].href.split('/');
        oA.href = href[0] + '//' + href[2] + '/download/' + href[3] + '/' + href[4];
        oA.target="_blank";
	var action = 'download';
        var file = oData[i].files[j].href.split('/').pop();
	var parts = file.split('.');
	var label = parts[0];
	var category = parts.pop();
        oA.onmouseup=new Function('ga_send("' + category + '", "' + action + '", "' + label + '"); return true;');
        oA.innerHTML = " " + oData[i].files[j].name + " &nbsp;";
        //oA.appendChild(document.createTextNode(" " + oData[i].files[j].name + " "));
        //oDIV.appendChild(document.createTextNode(" "));
      }
    }

    les02.setAttribute("loadedFiles", "true");
  }
  beingLoadedLesson=null;
}

//This function handles OnClick event on hint [Loading...]
function cancelLesLoad(){
  hideBeingLoadedLesson();
  open_lesson(beingLoadedLesson.getAttribute("less_id"));
  beingLoadedLesson=null;
  return false;
}

// =======================================================
//   LESSONS RELATED STUFF
// =======================================================

//Show hint [Loading...]
function showBeingLoadedLessons(){
  var oDIV = beingLoadedLessons.appendChild(document.createElement("div"));
  oDIV.className = sNodeLoadingClass;
  var oA = oDIV.appendChild(document.createElement("a"));
  oA.href = "#";
  oA.title = "Click to cancel..."
  oA.onclick = cancelLessLoad;
  var  oText = oA.appendChild(document.createTextNode(sCancelLoading));
}

//This function handles OnClick event on hint [Loading...]
function cancelLessLoad(){
  hideCurrLessons();
  //open_lesson(beingLoadedLesson.getAttribute("less_id"));
  return false;
}

//Hide hint [Loading...]
function hideCurrLessons(){
  if(is_ie){
    while(lessTab.rows.length > 3) lessTab.deleteRow();
  }else{
    for(var r=0;r<lessTab.childNodes.length;r++){
      if(lessTab.childNodes[r].id){
        lessTab.removeChild(lessTab.childNodes[r]);
        r--;
      }
    }
  }
}

//Remove all the selected options from url
function loadLessonsAll(){
		gCid = null;
		gDateF = null;
		gSString = null;
		sStartLessonsURL = null;
		if(document.search_form || window.lesLoader)
      loadLessons(null,null,null);
    else
      window.location.href = sIndexURL;
}

//Load URL with current settings
function loadURL(pURL){
	var surl = pURL;

	if(gCid) surl += "&CID=" + gCid;
	if(gDateF) surl += "&DF=" + gDateF;
	if(gSString) surl += "&SS=" + gSString;

	window.open(surl);

}

//Load subtree into hidden frame
function loadLessons(pCid, pPage, pDateF, pSString){
	var surl = sLessonsURL;
  if(pCid == 'undefined') pCid=null;

	if(window.lesLoader){

	  if( pCid || pDateF || pSString){
      sStartLessonsURL = null;
      gCid = pCid;
      gDateF = pDateF;
      gSString = pSString;
    }

    try{
      if(!gSString)
        document.forms['q_search_form'].SS.value='';
      else
        document.forms['q_search_form'].SS.value=gSString;
      if(!gCid) new_currNode('0');
      if(!gDateF) if(curCalCell){
        removeClass(curCalCell, "today");
        curCalCell = null;
      }
    }catch(e){}

		if(sStartLessonsURL != null){
			surl = sStartLessonsURL;
		}else{
			if(gCid) surl = surl + "&CID=" + gCid;
			if(gDateF) surl = surl + "&DF=" + gDateF;
			if(gSString) surl = surl + "&SS=" + gSString;
		}
		if(pPage) surl = surl + "&PAGE=" + pPage;

	  //alert(surl);

	  window.lesLoader.location = surl;
	}else{
    try{
      if(pCid){
		    document.search_form.CID.value = pCid;
      }else{
        document.search_form.CID.value = '';
      }
	}catch(e){
      if(pCid){
        window.location.href = sIndexURL + pCid;
      }else
      if(pDateF){
        window.location.href = sIndexURL + '&DF=' + pDateF;
      }
    }
  }
  //We will cancel loading of tree if it willn't have success during timeout
  //window.setTimeout("cancelLesLoadByTimeout('" + beingLoadedNode.id + "');", timeOut);
}

function buildLessons(oData,pPage,pLesCount,pLesPP){
  var i, j;
  var oRow, oCell, oFont, oImg, oDiv, oA;

	hideCurrLessons();
   for (i=0;i<oData.length;i++){

     oRow = add_row(lessTab);
     oRow.style.cursor="pointer";
     oRow.className="deactivated";
     oRow.title="less_" + oData[i].lId;
     oRow.id="less_" + oData[i].lId;
     oRow.meActivate = activate;
     oRow.meDeactivate = deactivate;
     oRow.meClick = open_lesson;
     oRow.setAttribute("lessonId", oData[i].lId)
     oRow.setAttribute("Expanded", "false")
     addHandler(oRow,'mouseover','meActivate');
     addHandler(oRow,'mouseout','meDeactivate');
 		 addHandler(oRow,'click','meClick');

     oCell = add_cell(oRow);
     if(oData[i].lRecent) oCell.style.color="Red";
     else oCell.style.color="SlateGray";
     oCell.appendChild(document.createTextNode(oData[i].lDate));

     oCell = add_cell(oRow);
     if(oData[i].lSecure){
 			oImg=oCell.appendChild(document.createElement('img'));
 			oImg.src="images/unlock.gif";
 			oImg.align="middle";
 			oImg.border="0";
 			oImg.hspace="0";
 			oImg.vspace="0";
 		 }
 		 oCell.appendChild(document.createTextNode(oData[i].lName));

     oCell = add_cell(oRow);
     oCell.align="center";
     oCell.appendChild(document.createTextNode(oData[i].lOLang));

     oCell = add_cell(oRow);
     oCell.appendChild(document.createTextNode(oData[i].lTLang));

     insertCheckImage(add_cell(oRow),oData[i].lVideo);
     insertCheckImage(add_cell(oRow),oData[i].lAudio);
     insertCheckImage(add_cell(oRow),oData[i].lText);
     insertCheckImage(add_cell(oRow),oData[i].lPict);

     if(oData[i].lLecturer || oData[i].lDescr){
 			 oRow = add_row(lessTab);
 			 oRow.id="les01_" + oData[i].lId;
 			 oCell = add_cell(oRow);
 			 oCell.colSpan = '8';
 			 oCell.bgColor = "#FBDB96";
 			 oRow.style.display="none";

 			 if(oData[i].lLecturer){
 				 oDiv=oCell.appendChild(document.createElement('div'));
 				 oDiv.style.color="SlateGray";
 				 oDiv.appendChild(document.createTextNode(lecturerName + ' '));
 				 oDiv=oDiv.appendChild(document.createElement('span'));
 				 oDiv.style.color="#006C8A";
 				 oDiv.appendChild(document.createTextNode(oData[i].lLecturer));
 			 }
 			 if(oData[i].lDescr){
 				 oDiv=oCell.appendChild(document.createElement('div'));
 				 oDiv.style.color="SlateGray";
 				 oDiv.appendChild(document.createTextNode(oData[i].lDescr));
 			 }
 		}

 		oRow = add_row(lessTab);
 		oRow.style.display="none";
 		oRow.id="les02_" + oData[i].lId;
    oRow.setAttribute("loadedFiles", "false")

 		oCell = add_cell(oRow);
 		oCell.bgColor = "#FBDB96";
 		oCell.colSpan = 8;

 		oDiv=oCell.appendChild(document.createElement('div'));
 		oDiv.id="tbl_" + oData[i].lId;
    oDiv.setAttribute("less_id", oData[i].lId);

    }

    if(pLesCount > 0){
 		oRow = add_row(lessTab);
 		oRow.id='sepp';
 		oRow.height='1';
 		oCell = add_cell(oRow);
 		oCell.height='1';
 		oCell.colSpan = 8;
        oCell.innerHTML = '<table border="0" width="100%" cellspacing="0" cellpadding="0" align="center" height="1"><tr><td bgcolor="#006C8A"><img src="images/pix.gif" border="0" width="1" height="1"></td></tr></table>';
    }

 		oRow = add_row(lessTab);
 		oRow.id='pctl';
 		oCell = add_cell(oRow);
 		oCell.align='right';
 		oCell.colSpan = 8;

    if(pLesCount > 0 && pPage > 1){
    	oA = oCell.appendChild(document.createElement('a'));
    	oA.setAttribute("href", 'javascript: loadLessons(null,' + (pPage - 1) + ');')
    	oA.appendChild(document.createTextNode('< ' + PAGECONTROL_PREV_PAGE));
    	oCell.appendChild(document.createTextNode(' | '));
		}

		var iFrom = (pLesCount == 0?0:(pLesPP * pPage) - (pLesPP - 1));
		var iTo = iFrom + pLesPP - 1;
		iTo = (iTo > pLesCount ? pLesCount : iTo);
 		oCell.appendChild(document.createTextNode(' ' + iFrom + ' - ' + iTo + ' ' + PAGECONTROL_OF + ' ' + pLesCount + ' ' + (pLesCount==1?PAGECONTROL_LESSON:PAGECONTROL_LESSONS) + ' '));

    if(pLesCount > 0 && iTo < pLesCount){
    	oCell.appendChild(document.createTextNode(' | '));
    	oA = oCell.appendChild(document.createElement('a'));
    	oA.setAttribute("href", 'javascript: loadLessons(null,' + (pPage + 1) + ');')
    	oA.appendChild(document.createTextNode(PAGECONTROL_NEXT_PAGE + ' >'));
		}

    if(dispLID != null){
    	open_lesson(null, dispLID);
    	dispLID=null;
		}
}

function add_row(oTab){
  if(is_ie) return oTab.insertRow();
  return oTab.appendChild(document.createElement("tr"));
}

function add_cell(oRow){
  if(is_ie) return oRow.insertCell();
  return oRow.appendChild(document.createElement("td"));
}

function insertCheckImage(cell, val){
	var oImg;
  cell.align="center";
  cell.valign="middle";
  oImg=cell.appendChild(document.createElement('img'));
	oImg.align="center";
	oImg.border="0";
	oImg.hspace="0";
	oImg.vspace="0";
  if(val) oImg.src=pCheck.src;
	else oImg.src=pEmpty.src;
}

function addHandler(target, eventName, handlerName) {
  if (target.addEventListener) {
    	target.addEventListener(eventName, function(e){ target[handlerName](e); }, false);
  } else if ( target.attachEvent ) {
    target.attachEvent("on" + eventName, function(e){target[handlerName](e);});
  } else {
    var originalHandler = target["on" + eventName];
    if ( originalHandler ) {
      target["on" + eventName] = function(e){originalHandler(e);target[handlerName](e);};
    } else {
      target["on" + eventName] = target[handlerName];
    }
  }
}

