﻿/*
  * Row selected in treegrid
  * Can be a row, or a document...
  */

var curBookID;
var curSearchXML;
var curTreeXML;

var neverPopup = false;                                  // Never, ever popup (deprecated?)

var PathTo_Documents = "dok/";                  // Relative path to document folder
var curDoc = "";                                               // Current document ID
var curExtAvail = "";                                        // Available extensions of current document
var curBookmarks = "";                                  // Available bookmarks of current document

var docChangedViaTree = false;

setTimeout("ekvMonitor(true, '')", 2000);               // Start monitoring function...


/* *********************************************************
	ekvMonitor()
	
		 - Checks if document inside frame changes,
			updates docinfo.
			
   ********************************************************* */
function ekvMonitor(loop, newDoc) {
	//
	// Check if document has changed...
	//
	if(docChangedViaTree) {
		refreshBookmarks();
		refreshExtensions();
		docChangedViaTree  = false;
		setTimeout("ekvMonitor(true, '')", 2000);
		return;
	}
	
	var frameDocID = getCurrentDocumentID();
	
	if(!loop) {
		if(newDoc != "check") {
			frameDocID = newDoc;
		} else {
			frameDocID = getCurrentDocumentID();
			refreshBookmarks();
			refreshExtensions();
		}
	} 

	
	
	if(curDoc != frameDocID) {
		// Document has changed
		
		// Update document information
		curExtAvail = getDocumentExtensions(frameDocID);
		curBookmarks = getDocumentBookmarks(frameDocID);
		curDoc = frameDocID;
		
		
		refreshBookmarks();
		refreshExtensions();
	}

	if(loop) {
		setTimeout("ekvMonitor(true, '')", 2000);
	}
}



/* *********************************************************
	getHandbokName()
	
	Selected bookname from current xml, and append i to the title...

   ********************************************************* */
function getHandbokName() {
	var HandbokName = gridTree.getUserData("1", "handbokname");
	document.title = "EK Viewer: " + HandbokName;
}







/* *********************************************************
	rowSelected()
	
		ARGUMENTS:
			rowID					-	The selected row
			colIndex					-	Selected column

   ********************************************************* */
function rowSelected(rowID, colIndex) {
	
	//
	// Only open documents, document row id's have a _ in them...
	//
	if(rowID.indexOf('_') < 0)
		return;


	//
	// Determine the document ID
	//
	var docID = rowID.substring(rowID.indexOf("_")+1);
	var docExt = "";
	var docExtAvail = "";

	//
	// Determine if we are searching, or browsing the tree
	//
	var isSearching = false;
	if(document.getElementById("SearchGrid").style.display == "block") {
		isSearching = true;
	}
	
	//
	// Hide buttons on document header
	//
	document.getElementById("btnOpenDoc_External").style.display = "none";
	

	//
	// Is document a file, or external reference?
	//
	if(rowID.indexOf('dok') < 0) {
		// This is an external document, show external link button
		var url = docID;
		document.getElementById("btnOpenDoc_External").style.display = "block";
		document.getElementById("btnOpenDoc_External").onclick = function() { openPopup(url, false); };

		// Open "external" information page in frame...
		docID = "external";
		docExt = "internal";
	} else {
		//
		// Document is a file...
		//

		//
		// Get list of available extensions and bookmarks.
		//
		if(isSearching) {
			docExtAvail = gridSearch.getUserData(rowID,'extensions');	// gridTree have the same row id's as gridSearch...
			curBookmarks = gridSearch.getUserData(rowID,'bookmarks');
		} else {
			docExtAvail = gridTree.getUserData(rowID,'extensions');	// gridTree have the same row id's as gridSearch...
			curBookmarks = gridTree.getUserData(rowID,'bookmarks');
		}
		

		var arrExtensions = docExtAvail.split(",");
		
		
		if(docExtAvail.indexOf("pdf") > -1) {
			docExt = "pdf";
		} else if(docExtAvail.indexOf("html") > -1) {
			docExt = "html";
		} else if(docExtAvail.indexOf("htm") > -1) {
			docExt = "htm";
		} else {
			// Select random :) Or actually, the last...
			for (var i = 0; i < arrExtensions.length; i++) {
				docExt = arrExtensions[i];
			}
		}
	}

	//
	// Set current document,
	//
	curDoc = docID;
	curExtAvail = docExtAvail;
	
	
	
	//
	// Open the document
	//
	openDocument(docID, docExt, false, false);
}








/* *********************************************************
	openDocument()
	
		ARGUMENTS:
			docID					-	Document ID
			docExt					-	Extension to open
			hideDocHeaderLinks	-	Hide all buttons on the doc header.
			forcePopup				-	Force document to popUp (Will NOT override neverPopup)
			

   ********************************************************* */

function openDocument(docID, docExt, hideDocHeaderLinks, forcePopup) {
	//
	// Hide buttons on document header
	//
	if(hideDocHeaderLinks) {
		document.getElementById("btnOpenDoc_External").style.display = "none";
	}
	
	if( (docID == null) || (docID.length == 0) || (docExt == null) || (docExt.length == 0)) {
		alert('Feil oppstod ved åpning av dokument, ingen referanse til dokumentet gitt.');
		return;
	}
	
	// Get iFrame...
	var objDocument = document.getElementById("objDocument");
	
	
	var openDoc;
	var popup = true;
	
	
	// Use lowercase doc extensions
	docExt = docExt.toLowerCase();
	
	//
	// Determine document URI
	//
	var internalDocument = false;
	if ( (docID == "") || (docExt == "") ) {
		openDoc = "error.html";
		docExt = "html";
		internalDocument = true;
	} else if (docExt == "internal") {
		openDoc = docID + ".html";
		docExt = "html";		
		internalDocument = true;
	} else if (docExt == "n/a") {
		openDoc = "notfound" + ".html";
		docExt = "html";		
		internalDocument = true;
	} else if (docExt == "pdf") {
		openDoc = "pdfProxy.htm?" + docID;
		internalDocument = false;
	} else {
		openDoc = PathTo_Documents + docID + "." + docExt;
		internalDocument = false;
	}
		
	//
	// Determine if we can show this file in the iFrame (popup=false)
	//
	switch (docExt) {
		case "htm":
		case "html":
		case "jpg":
		case "jpeg":
		case "png":
		case "gif":
		case "pdf":
			popup = false;
			break;
		
		default:
			popup = true;
	}
	
	if(forcePopup) {
		popup = true;
	}	
	

	//
	// Open the document
	//
	if(popup) {
		openPopup(openDoc, false);
		return;
	}
	
	//
	// Update home button onclick event
	//
	document.getElementById("btnNavHome").style.display = "none";
	if(!popup && !internalDocument){
		document.getElementById("btnNavHome").style.display = "block";
		document.getElementById("btnNavHome").onclick = function() {openDocument(docID, docExt, false, false); }
	}
	
	
	//
	// Update iframe with document
	//
	objDocument.src = openDoc;
	
	//
	// Refresh extensions and bookmarks
	//
	docChangedViaTree = true;
	//refreshExtensions();
	//refreshBookmarks();
}








/* *********************************************************
	refreshExtensions()
	
		Refreshes links to other formats (top right)

   ********************************************************* */

function refreshExtensions() {

	var div = document.getElementById("divExtensionLine");
	div.innerHTML = "";

	var docID =  getCurrentDocumentID();
	var availableExtensions =  getDocumentExtensions(docID);
	
	
	if(availableExtensions.length > 0) {
		var extMenu = "";
		var arrExt = availableExtensions.split(',');
		
		extMenu += "<table  cellpadding='0' cellspacing='0' background=\"img/rightHeadBg.jpg\">";
		extMenu += " <tr>";
		
		var i;
		for(i = 0; i < arrExt.length ; i++) {
			extMenu += "  <td style='padding-left: 2px; padding-right: 8px;'  >"
			extMenu += "   <a href=\"javascript:openPopup('" + PathTo_Documents  + docID + "." + arrExt[i] + "', 'true')\">"
			extMenu += "    <img src='img/" + extIconFile(arrExt[i]) + "' border='0'>"
			extMenu += "   </a>"
			extMenu += "  </td>";
		}
		extMenu += "  </tr>";
		extMenu += " </table>";		
		
		div.innerHTML = extMenu;	
	}
}









/* *********************************************************
	refreshBookmarks()
	
	
		ARGUMENTS:
			none
		
			
   ********************************************************* */
function refreshBookmarks() {

	var div = document.getElementById("divBookmarkLine");

	div.innerHTML = "";	

	var bmMenu = "";
	
	if((curBookmarks == null) || (curBookmarks.indexOf("||") == -1)) {
		bmMenu = "";
	} else {
		var arrPairs = curBookmarks.split("||");

		bmMenu += "<table  cellpadding='0' cellspacing='0'>";
		bmMenu += " <tr>";

		// Build bookmark menu
		for(var p = 0; p<arrPairs.length; p++) {
			var arrTokens = arrPairs[p].split(">>");
			
			if(arrTokens.length == 2) {
				bmMenu += "  <td style='padding-left: 15px;'><a href=\"javascript:gotoBookmark('"+arrTokens[0]+"')\">";
				bmMenu +=  arrTokens[1].replace(' ', '&nbsp;');
				bmMenu += "  </a></td>";
			}
		}

		bmMenu += "  </tr>";
		bmMenu += " </table>";		
	}
	
	
	// Present the bookmarks
	div.innerHTML = bmMenu;
}








/* *********************************************************
	gotoBookmark()
	
		Reads the current source of iframe, strips anchors, and adds
		a new anchor with the bookmark...

		ARGUMENTS:
			href		-	Anchor to apply
			
   ********************************************************* */
function gotoBookmark(href) {

	// Find iFrame...
	var objDocument = document.getElementById("objDocument");
	var curSrc = objDocument.src;
	
	// We need to remove any other bookmarks from the src
	if(curSrc.indexOf('#') > -1) {
		curSrc = curSrc.substring(0,curSrc.indexOf('#'));
	}
	var objDocument = document.getElementById("objDocument");
			

	// This way turned out to be the best way, even works on IE.
	objDocument.src = "about:blank";
	setTimeout("setFrameURI('"+curSrc + href +"')", "200");
}



/* *********************************************************
	setFrameURI()
		Called by gotoBookmark by a timeout, sets src
		of iframe.
		
		ARGUMENTS:
			url	-	URI to open
			
   ********************************************************* */

function setFrameURI(url) {
	var objDocument = document.getElementById("objDocument");

	url = url;
	//alert("HOI" + url);

	objDocument.src = url;
}





/* *********************************************************
	openPopup()
	
		Pop's up a window with given URL

		ARGUMENTS:
			url		-	URL To open
			
   ********************************************************* */

function openPopup(url, silent) {
	var objDocument = document.getElementById("objDocument");

	if(!neverPopup) {
		window.open(url);

		if(!silent) {
			objDocument.src = "window.html?" + curDoc;
		}
	} else {
		objDocument.src = url;
	}
}







/* *********************************************************
	processGETs
	
		Reads GET variables from document.location, and performs
		various actions like automatic search and document loading.

		Function is called by body.onLoad

	********************************************************* */
	 
function processGETs() {
	try {
		var loc = document.location.toString();
		if(loc.indexOf("?") > -1) {
			var strGets = loc.substring(loc.indexOf("?")+1);
			var arrGets = strGets.split("&");
		
			for(var i = 0; i<arrGets.length; i++) {

				if(arrGets[i].indexOf("=") > -1) {
					var getKey = arrGets[i].split("=")[0];
					var getVal = arrGets[i].split("=")[1];
				
				
					if( (getKey == "fs") && (getVal != null) && (getVal.length > 0) ) {
						//
						// Do a freetext search...
						//
						document.getElementById("chkFreetextSearch").checked = true;
						document.getElementById("txtSearchField").value = getVal;
						setTimeout('doSearch()', 200);
					}
					if( (getKey == "ts") && (getVal != null) && (getVal.length > 0) ) {
						//
						// Do a freetext search...
						//
						document.getElementById("chkFreetextSearch").checked = false;
						document.getElementById("txtSearchField").value = getVal;
						setTimeout('doSearch()', 200);
					}
					
					if( (getKey == "doc") && (getVal != null) && (getVal.length > 0) && (getVal.indexOf(".") > -1) ) {
						//
						// Open document
						//
						var docID = getVal.substring(0, getVal.indexOf("."));
						var docExt = getVal.substring(getVal.indexOf(".")+1);
						
						openDocument(docID, docExt, false, false);
					}
					
					if( (getKey == "neverPopup") && (getVal != null) && (getVal.length > 0) && (getVal == "true") ) {
						//
						// Disable popups
						//
						neverPopup = true;
					}

					if( (getKey == "hideNavigation") && (getVal != null) && (getVal.length > 0) && (getVal == "true") ) {
						//
						// Disable left navigation menu
						//
						document.getElementById('tdColLeftHeader').style.display = 'none';
						document.getElementById('colLeft').style.display = 'none';
					}					

				}
			}
		}
	} catch (e) {
		alert('Feil oppstod ved automatisk handling: ' + e);
	}
}








/* *********************************************************
	treeBtnClicked
	
		If searhcgrid is active, the user is returned to the tree.
		
		If treegrid is active, we collapse everything except root-
		folders. Tree state before click is saved in cookie, and restored
		upon a subsequent click.

   ********************************************************* */
var toggleTreeExpand = true;
function treeBtnClicked() {
	var SearchDisplay = document.getElementById('SearchGrid').style.display;

	if(SearchDisplay.indexOf("block") > -1) {
		endSearch();
	} else {
		if(toggleTreeExpand) {
			//
			// Expand all roots...
			//
			
			// Save state...
			gridTree.saveOpenStates('ekvCurTreeState', '');
			
			// Collapse all folders
			gridTree.collapseAll()
			
			// Open folders...

			var HandbokRoots = gridTree.getUserData("1", "roots").split(',');
			for(var i = 0; i < HandbokRoots.length ; i ++) {
				gridTree.openItem(HandbokRoots[i]);
			}
			
			toggleTreeExpand = false;
		} else {
			//
			// Restore previous...
			//
			gridTree.loadOpenStates('ekvCurTreeState', ''); // load open state of TreeGrid from cookies
			toggleTreeExpand = true;
		}

	}
}








/* *********************************************************
	InitializeBookSelector()
	
		Create select control for selecting book.

   ********************************************************* */
function InitializeBookSelector() {
	var oldSel = document.getElementById("BookSelector");
	var newSel = document.createElement('select');
	newSel.id = "BookSelector";
	newSel.onchange = function() { ChangeBook(); };

	//var availableBooks = "EKRD0014¤Morten|";
	var arrBooks  = availableBooks.split("|");
	
	var defSet = false;
	for(var i=0;i<arrBooks.length; i++) {
		if(arrBooks[i].length > 0) {
			var bookID = arrBooks[i].split("#")[0];
			var bookName = arrBooks[i].split("#")[1];

			var option = document.createElement('option');
			option.appendChild(document.createTextNode(bookName));
			
			if(i == 0) {
				curBookID = bookID;
				option.setAttribute('selected', 'selected');
			}

			if(bookID.substring(0, 1) == "*") {
				bookID = bookID.substring(1);
				defSet = true;
				curBookID = bookID;
				option.setAttribute('selected', 'selected');
			}


			option.setAttribute('value', bookID);
			newSel.appendChild(option);
		}
	}

	
	oldSel.parentNode.replaceChild(newSel, oldSel);
}








/* *********************************************************
	ChangeBook()
	
		Changes the current book of the viewer...

   ********************************************************* */
function ChangeBook() {

	//
	// Show tree grid, hide search and reset searchfield...
	//
	endSearch();
	
	//
	// Get selected book from select box...
	//
	var selBook = document.getElementById("BookSelector");
	curBookID = selBook.options[selBook.selectedIndex].value;

	//
	// Set paths to XML files for this book...
	//
	curSearchXML = "search_" + curBookID + ".xml";
	curTreeXML = "tree_" + curBookID + ".xml";
	
	//
	// Initialize tree and searchgrid...
	//
	initTreeGrid(curTreeXML);
	initSearchGrid(curSearchXML);
	
	//
	// Update title with bookname...
	//
	setTimeout('getHandbokName()', 100);
}







/* *********************************************************
	KeyCheck()
	
		Search when enter key is pressed in SearchField...

   ********************************************************* */
function KeyCheck(e) { 

	var IsEnter = false;
	
	if(window.event) {
		if (e.keyCode == "13") 
			IsEnter = true;
	} else if(e.which) {
		if (e.which == "13")
			IsEnter = true;
	}

	if(IsEnter) { 
		var obj = document.getElementById('btnSearch'); 
		if (obj != null) { 
			obj.focus(); 
		} 
	}
} 





/* *********************************************************
	getCurrentDocumentID()
	
		Checks if current document in iframe is curDoc (last openend by treegrid), if not
		it returns the currect document id.

   ********************************************************* */
function getCurrentDocumentID() { 

	var objDocument = document.getElementById("objDocument");
	var iframeURL;
	
	

	try {
		iframeURL = objDocument.contentDocument.location;
	} catch(e) {
		try {
			iframeURL = objDocument.contentWindow.location;
		} catch (e) {
			//alert('Kan ikke åpne utskriftsvennlig versjon, dette skyldes mest sansynlig at dokumentet er et ekstern dokument, og ikke ligger sammen med håndboken. Feilmelding: ' + e);
			return;
		}
	}
	
	
	try {
		var foobar = iframeURL.toString();
	} catch(e) {
			//alert('Kan ikke åpne utskriftsvennlig versjon, dette skyldes mest sansynlig at dokumentet er et ekstern dokument, og ikke ligger sammen med håndboken.');
			return;
	}
	
	if(iframeURL.toString().indexOf(curDoc) > -1) {
		//
		// DOCUMENT LOADED IS CURRENT
		//
		return  curDoc;

	} else {
		//
		// DOCUMENT IN IFRAME IS DIFFERENT THAN CURRENT DOCUMENT
		//
		var docID;
		
		// Check if internal document
		if(iframeURL.toString().indexOf("info.html") > -1) {
			return "info";
		}
		
		// Get document id shown in iframe
		var rxDocId = new RegExp('dok[0-9]{5}\.[a-z]{1,5}');
		var rxDocIdRes = rxDocId.exec(iframeURL);
		if(rxDocIdRes != null) {
			var lm = rxDocIdRes.length - 1;
			if(rxDocIdRes[lm].toString().indexOf(".") > 0) {
				docID = rxDocIdRes[lm].toString().split('.')[0];
			}
		}
		
		
		
		if(docID == null) {
			return curDoc;
		}
		
		if(docID.length != 8) {
			return curDoc;
		}
		
		return docID;
	}
	
	return "";
} 

function getDocumentRowID(docID) {
		if(docID == curDoc) {
			return curExtAvail;
		}
		
		
		var exts = "";
		
		gridTree.forEachRow(function(id){
			if(id.indexOf('_') > 0) {
				if(id.substring(id.indexOf("_")+1) == docID) {
					// Found document in gridTree, get extensions...
					
					exts = gridTree.getUserData(id, "extensions");
				}
			}
		});
		
		return exts;
}

	
function getDocumentExtensions(docID) {
		if(docID == curDoc) {
			return curExtAvail;
		}
		
		
		var exts = "";
		
		gridTree.forEachRow(function(id){
			if(id.indexOf('_') > 0) {
				if(id.substring(id.indexOf("_")+1) == docID) {
					// Found document in gridTree, get extensions...
					
					exts = gridTree.getUserData(id, "extensions");
				}
			}
		});
		
		return exts;
}

function getDocumentBookmarks(docID) {
		if(docID == curDoc) {
			return curBookmarks;
		}
		
		var bmDef = "";
		
		gridTree.forEachRow(function(id){
			if(id.indexOf('_') > 0) {
				if(id.substring(id.indexOf("_")+1) == docID) {
					// Found document in gridTree, get extensions...
					
					bmDef = gridTree.getUserData(id, "bookmarks");
				}
			}
		});
		
		if(bmDef == null)
			bmDef = "-";
		
		return bmDef;
}



function extPrintName(ext) {
	switch(ext) {
	
		case "pdf":
			return "PDF";
			break;
			
		case "doc":
		case "docx":
		case "docm":
			return "Word";
			break;
			
		case "xls":
		case "xlsx":
		case "xlsm":
			return "Excel";
			break;
			
		case "ppt":
		case "pptx":
			return "Powerpoint";
			break;
			
		case "vsdx":
		case "vsd":
			return "Visio";
			break;

		case "htm":
		case "html":
			return "Nettleser";
			break;

		case "jpeg":
		case "jpg":
		case "gif":
		case "png":
		case "tif":
			return "Bildebehandler";
			break;

		case "mp3":
		case "aac":
		case "wav":
		case "wma":
			return "Lydfil";
			break;
			
		case "mpg":
		case "wmv":
		case "avi":
		case "mkv":
			return "Video fil";
			break;
			
			
		default:
			return "Annet";
	}
			
}

function extIconFile(ext) {
	switch(ext) {
	
		case "pdf":
			return "ext_pdf.gif";
			break;
			
		case "doc":
		case "docx":
		case "docm":
			return "ext_word.gif";
			break;
			
		case "xls":
		case "xlsx":
		case "xlsm":
			return "ext_excel.gif";
			break;
			
		case "ppt":
		case "pptx":
			return "ext_powerpoint.gif";
			break;
			
		case "vsdx":
		case "vsd":
			return "ext_visio.gif";
			break;

		case "htm":
		case "html":
			return "ext_html.gif";
			break;

		case "jpeg":
		case "jpg":
		case "gif":
		case "png":
		case "tif":
			return "ext_image.gif";
			break;

		case "mp3":
		case "aac":
		case "wav":
		case "wma":
			return "ext_sound.gif";
			break;
			

		case "mpg":
		case "wmv":
		case "avi":
		case "mkv":
			return "ext_video.gif";
			break;
			
		default:
			return "ext_unknown.gif";
	}
	
	return "ext_unknown.gif";
			
}
