
var waiting = "<img src='loading.gif' /> Čekám na obsah...";
var isIE = false;
String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}
function sack(file) {
	this.timeoutID="";
	this.xmlhttp = null;
	this.resetData = function() {
		this.method = "POST";
  		this.queryStringSeparator = "?";
		this.argumentSeparator = "&";
		this.URLString = "";
		this.encodeURIString = true;
  		this.execute = false;
  		this.element = null;
		this.elementObj = null;
		this.requestFile = file;
		this.vars = new Object();
		this.responseStatus = new Array(2);
		this.prevCaching = true;
		this.showQueryStringSeparator =  true;
  	};
	this.resetFunctions = function() {
  		this.onLoading = function() { };
  		this.onLoaded = function() { };
  		this.onInteractive = function() { };
  		this.onCompletion = function() { };
  		this.onError = function() { };
		this.onFail = function() { };
	};
	this.reset = function() {
		this.resetFunctions();
		this.resetData();
	};
	this.createAJAX = function() {
		try {
						 
			  if (window.ActiveXObject)  isIE = true;
			  
			this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e1) {
			try {
				this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
				
			} catch (e2) {
				this.xmlhttp = null;
			}
		}
		if (! this.xmlhttp) {
			if (typeof XMLHttpRequest != "undefined") {
				this.xmlhttp = new XMLHttpRequest();
			} else {
				this.failed = true;
			}
		}
	};
	
	this.timesUp = function() {
	 if (this.xmlhttp)	{this.xmlhttp.abort();}
	}
	this.setVar = function(name, value){
		this.vars[name] = Array(value, false);
	};
	this.encVar = function(name, value, returnvars) {
		if (true == returnvars) {
			return Array(encodeURIComponent(name), encodeURIComponent(value));
		} else {
			this.vars[encodeURIComponent(name)] = Array(encodeURIComponent(value), true);
			return true;
		}
	}
	this.processURLString = function(string, encode) {
		encoded = encodeURIComponent(this.argumentSeparator);
		regexp = new RegExp(this.argumentSeparator + "|" + encoded);
		varArray = string.split(regexp);
		for (i = 0; i < varArray.length; i++){
			urlVars = varArray[i].split("=");
			if (true == encode){
				this.encVar(urlVars[0], urlVars[1]);
			} else {
				this.setVar(urlVars[0], urlVars[1]);
			}
		}
	}
	this.createURLString = function(urlstring) {
		if (this.encodeURIString && this.URLString.length) {
			this.processURLString(this.URLString, true);
		}
		if (urlstring) {
			if (this.URLString.length) {
				this.URLString += this.argumentSeparator + urlstring;
			} else {
				this.URLString = urlstring;
			}
		}
		// prevents caching of URLString
		if (this.prevCaching) this.setVar("rndval", new Date().getTime());
		urlstringtemp = new Array();
		for (key in this.vars) {
			if (false == this.vars[key][1] && true == this.encodeURIString) {
				encoded = this.encVar(key, this.vars[key][0], true);
				delete this.vars[key];
				this.vars[encoded[0]] = Array(encoded[1], true);
				key = encoded[0];
			}
			urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
		}
		if (urlstring){
			this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator);
		} else {
			this.URLString += urlstringtemp.join(this.argumentSeparator);
		}
	}
	this.runResponse = function() {
		eval(this.response);
	}
	this.runAJAX = function(urlstring) {
		if (this.failed) {
			this.onFail();
		} else {
			this.createURLString(urlstring);
			if (this.element) {
				this.elementObj = document.getElementById(this.element);
			}
			if (this.xmlhttp) {
				var self = this;
				this.timeOutID = setTimeout(this.timesUp,5000);
				if (this.method == "GET") {
					if (this.showQueryStringSeparator)
					totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
					else
					totalurlstring = this.requestFile + this.URLString;
				
					this.xmlhttp.open(this.method, totalurlstring, true);
				} else {
					this.xmlhttp.open(this.method, this.requestFile, true);
					try {
						this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
					} catch (e) { }
				}
				this.xmlhttp.onreadystatechange = function() {
					switch (self.xmlhttp.readyState) {
						case 1:
							self.onLoading();
							break;
						case 2:
							self.onLoaded();
							break;
						case 3:
							self.onInteractive();
							break;
						case 4:
							clearTimeout(self.timeoutID);
							self.response = self.xmlhttp.responseText;
							self.responseXML = self.xmlhttp.responseXML;
							self.responseStatus[0] = self.xmlhttp.status;
							self.responseStatus[1] = self.xmlhttp.statusText;
							if (self.execute) {
								self.runResponse();
							}
							if (self.elementObj) {
								elemNodeName = self.elementObj.nodeName;
								elemNodeName.toLowerCase();
								if (elemNodeName == "input"
								|| elemNodeName == "select"
								|| elemNodeName == "option"
								|| elemNodeName == "textarea") {
									self.elementObj.value = self.response;
								} else {
									self.elementObj.innerHTML = self.response;
								}
							}
							if (self.responseStatus[0] == "200") {
								self.onCompletion();
							} else {
								self.onError();
							}
							self.URLString = "";
							break;
					}
				};
				this.xmlhttp.send(this.URLString);
			}
		}
	};
	this.reset();
	this.createAJAX();	
}
function checkAvail(containerId, PID, flag, UNID) {
	/**
	 *  Nastavit AJAX premmenne
	 */
	 
	var ajaxIndex = 1; //zatial 1
	var url="";
	var prefix = "/" + URL + "/checkAvailability?OpenAgent&pid=" + PID;
	if (flag=="D") 
	 url = prefix +"&act=a";
	else 
	 if (flag=="DC")
	url = prefix +"&act=a&db=cesty";
	else 
	 if (flag=="DP")
	url = prefix +"&act=a&db=proj";
	 
	 else
		 url = prefix;
	if (UNID!=="" && UNID!=undefined) {
		url = url + "&unid=" + UNID;
	}
		
 	ajaxObjects = new Array();
 	ajaxObjects[ajaxIndex] = new sack();
 	document.getElementById(containerId).innerHTML = waiting;
 	ajaxObjects[ajaxIndex].onCompletion = function(){ displayAvailRes(containerId,ajaxIndex, flag); };
 	
 	ajaxObjects[ajaxIndex].requestFile = url;	// Specifying which file to get
	ajaxObjects[ajaxIndex].runAJAX();
}
function displayAvailRes(containerId, ajaxIndex, flag) {
	var result = ajaxObjects[ajaxIndex].response;
 	eval(" var exemplarTable = " + result);
	
	var container = document.getElementById(containerId);
 	if (container!==null){
 		
 	//result in JSON Format - have to create Table for seeing and links for reservation of the things!
 	/***
 	 * 
 	 *  Podla formy sa vyberie zobrazovacia funkcia!
 	 *  exemplarTable.form = Mono
 	 *  = Volume
 	 *  = Issue
 	 * 
 	 */
 	 
 	 if ((flag===null) | (flag==" ") | (flag==="")){
 	 if (exemplarTable.form == "Mono") displayMono(container, exemplarTable);
 	 if (exemplarTable.form == "Volumes") displayVolumes(container, exemplarTable);
  	 if (exemplarTable.form == "Issues") displayIssues(container, exemplarTable);
 	 	
 	 }
 	 else
 	 {
 	 	displayAvail(container, exemplarTable);
 	 }
 	 
 	 
  	 
  	 //  if (exampleTable.form == "Multimedia") displayMultimedia(container, exemplarTable);
 	}
 	 
 	}
 	
 	
function showIssues(containerId, PID) {
	/**
	 *  Nastavit AJAX premmenne
	 */
	 
	var ajaxIndex = 1; //zatial 1
	var url = "/" + URL + "/checkAvailability?OpenAgent&id=" + PID;
 	ajaxObjects = new Array();
 	ajaxObjects[ajaxIndex] = new sack();
 	document.getElementById(containerId).innerHTML = waiting;
 	ajaxObjects[ajaxIndex].onCompletion = function(){ displayAvailRes(containerId,ajaxIndex,''); };
 	
 	ajaxObjects[ajaxIndex].requestFile = url;	// Specifying which file to get
	ajaxObjects[ajaxIndex].runAJAX();
}
 	
 	
function displayVolumes(container, exemplarTable) {
 		
 		var i=0;
 		var j=0;
 		var tblString = "";
		tblString = "<table id=\"exemplars\" class=\"exemdata\">";
	
		
		tblString = tblString + "<thead><tr>" +
				"<th width=\"80\" class=\"\">Ročník</th>" +
				"<th width=\"80\" class=\"\">Místo uložení</th>" +
				"<th width=\"80\" class=\"\">Signatura</th>" +
				"<th width=\"100\" class=\"\">Externí uživatel</th>" +
				"<th width=\"100\" class=\"\">Interní uživatel</th>" +
				"<th width=\"100\" class=\"\">Stav</th>"+
				"<th width=\"100\" class=\"\">Chybějící čísla</th>"+
				"<th width=\"120\" class=\"\">Rezervace</th></tr></thead>" ;
			
		tblString = tblString + "<tbody>";
		
		exemplarTable.items.sort(sortCaseInsensitiveVol);
		
 		for (i=0; i<exemplarTable.items.length; i++){
 					tblString = tblString + "<tr>";
 					tblString = tblString + "<td>" + exemplarTable.items[i].volume + "</td>";	
 					tblString = tblString + "<td>" + exemplarTable.items[i].storage + "</td>";	
 					tblString = tblString + "<td>" + exemplarTable.items[i].mark + "</td>";	
 					tblString = tblString + "<td>" + exemplarTable.items[i].extloantype + "</td>";	
 					tblString = tblString + "<td>" + exemplarTable.items[i].intloantype + "</td>";	
 					tblString = tblString + "<td>" + exemplarTable.items[i].status + "</td>";
 					 					
 					if (exemplarTable.items[i].pid==="" & exemplarTable.items[i].storage!="Vazba" & exemplarTable.items[i].storage!="Nedostupno") {
 					tblString = tblString + "<td></td>";
 					tblString = tblString + "<td><a href=\"javascript:showIssues('availDetails','"+ exemplarTable.items[i].id + "'); \">Rezervovat lze jednotlivá čísla</a></td>";
 					}
 					else
 					{
 						if (exemplarTable.items[i].missing!=null){ 						
 							var missing = exemplarTable.items[i].missing.toString();
 							tblString = tblString + "<td>" + missing +"</td>";
 						}
 						else { 
 							tblString = tblString + "<td></td>"; 
 						}
 					
 					if (exemplarTable.items[i].id!="") {
 						tblString = tblString + "<td><a href=\"/" + E_URL + "/main?ReadForm&op=cr&id=" + exemplarTable.items[i].id + "\">Rezervovat ročník</a></td>";
 					}
 					else {
 						tblString = tblString + "<td></td>";
 					}
 					
 					}
 					
 					tblString = tblString + "</tr>";
 		}
 		tblString = tblString + "</tbody>";
	 	tblString = tblString +  "</table>";				
 	 	
 	container.innerHTML = tblString;	
 			
 	}
 	
function displayIssues(container, exemplarTable) {var i=0;
 		var j=0;
 		var tblString = "";
 		
 		tblString = "<h3>Ročník : " + exemplarTable.volume + "</h3>";
 		
 		
		tblString = tblString + "<table id=\"exemplars\" class=\"exemdata\">";
	
		
		tblString = tblString + "<thead><tr>" +
				"<th width=\"80\" class=\"\">Číslo</th>" +
				"<th width=\"100\" class=\"\">Externí uživatel</th>" +
				"<th width=\"100\" class=\"\">Interní uživatel</th>" +
				"<th width=\"100\" class=\"\">Stav</th>"+
				"<th width=\"120\" class=\"\">Rezervace</th></tr></thead>" ;
			
		tblString = tblString + "<tbody>";
		exemplarTable.items.sort(sortCaseInsensitiveIssue);
		
 		for (i=0; i<exemplarTable.items.length; i++){
 					tblString = tblString + "<tr>";
 					tblString = tblString + "<td>" + exemplarTable.items[i].issue + "</td>";	
 					tblString = tblString + "<td>" + exemplarTable.items[i].extloantype + "</td>";	
 					tblString = tblString + "<td>" + exemplarTable.items[i].intloantype + "</td>";	
 					tblString = tblString + "<td>" + exemplarTable.items[i].status + "</td>";	
					if (exemplarTable.items[i].pid!=="" && exemplarTable.items[i].status !== "ztraceno" ) tblString = tblString + "<td><a href=\"/" + E_URL + "/main?ReadForm&op=cr&pid=" + exemplarTable.items[i].pid + "\"> Rezervovat </a></td>"; else tblString = tblString + "<td></td>";
 					tblString = tblString + "</tr>";
 		}
 		tblString = tblString + "</tbody>";
	 	tblString = tblString +  "</table>";				
 	 	
 	container.innerHTML = tblString;
 /*	var objDiv = document.getElementById('availBottom');
 	//objDiv.scrollTop = objDiv.scrollHeight;
 	if(objDiv.scrollTop == (objDiv.scrollHeight - objDiv.offsetHeight)){
	blnPinScrollbar = true
	}
	if(blnPinScrollbar){
	objDiv.scrollTop = objDiv.scrollHeight
	}
 	*/
 	window.scrollBy(0, window.innerHeight ? window.innerHeight : 
document.body.clientHeight);
 
 	}
 	
 	
function displayAvail(container, exemplarTable) {
 		var i=0;
 		var j=0;
 		var tblString = "";
 		var firstHeadClmn = "";
		var	firstBodyClmn = "";
 		//tblString = "<h3>Dostupnost dokumentu :</h3>";
 		tblString = "";
 		
		tblString = tblString + "<table id=\"exemplars\" class=\"exemdata\">";
		sufix = "";
		// prvy sa lisi <- podla typu
		if (exemplarTable.form=="Mono") { 
				firstHeadClmn = "<th width=\"80\" class=\"\">Signatura</th>" + "<th width=\"80\" class=\"\">Přír. číslo</th>"
				firstBodyClmn = "<td>" + exemplarTable.items[0].mark + "</td>" + "<td>" + exemplarTable.items[0].acq_no + "</td>";}
		if (exemplarTable.form=="Volume"){
				 firstHeadClmn = "<th width=\"80\" class=\"\">Ročník</th>";
				 firstBodyClmn = "<td>" + exemplarTable.items[0].volume + "</td>";				 
		}
		
		if (exemplarTable.form=="Issue") { 
				 firstHeadClmn = "<th width=\"80\" class=\"\">Číslo</th><th width=\"80\" class=\"\">Ročník</th><th width=\"80\" class=\"\">Signatura</th>";
				 firstBodyClmn = "<td>" + exemplarTable.items[0].issue + "</td>" + "<td>" + exemplarTable.items[0].volume + "</td>" + "<td>" + exemplarTable.items[0].mark + "</td>";				 
		}
				
		if (exemplarTable.form=="cesty") {
			sufix = "&db=cesty";	
			firstHeadClmn = "<th width=\"80\" class=\"\">Místo uložení</th>";
			firstBodyClmn = "<td>" + exemplarTable.items[i].storage + "</td>";
 					
		}
//				"<th width=\"80\" class=\"\">Přír. číslo</th>" + 		
//"<th width=\"80\" class=\"\">Signatura</th>" + 	
//tblString = tblString + "<td>" + exemplarTable.items[0].mark + "</td>";	
		
		tblString = tblString + "<thead><tr>" +
				firstHeadClmn +				
				"<th width=\"100\" class=\"\">Externí uživatel</th>" +
				"<th width=\"100\" class=\"\">Interní uživatel</th>" +
				"<th width=\"100\" class=\"\">Stav</th>"+
				"<th width=\"120\" class=\"\">Rezervace</th></tr></thead>" ;
			
		tblString = tblString + "<tbody>";
		 		
 					tblString = tblString + "<tr>";
 					tblString = tblString + firstBodyClmn;
						
 					tblString = tblString + "<td>" + exemplarTable.items[0].extloantype + "</td>";	
 					tblString = tblString + "<td>" + exemplarTable.items[0].intloantype + "</td>";	
 					tblString = tblString + "<td>" + exemplarTable.items[0].status + "</td>";	
					// tblString = tblString + "<td><a href=\"/" + E_URL + "/main?ReadForm&op=cr&pid=" + exemplarTable.items[i].pid + sufix + "\"> Rezervovat </a></td>";
					if (exemplarTable.items[i].pid=="") {
 					tblString = tblString + "<td>Není možné rezervovat.</td>";
 					}
 					else { 					
 					tblString = tblString + "<td><a href=\"/" + E_URL + "/main?ReadForm&op=cr&pid=" + exemplarTable.items[i].pid + "&unidext=" + exemplarTable.items[i].unid_ext  + "\"> Rezervovat </a></td>";
 					}
 					
 					tblString = tblString + "</tr>";
 		
 		tblString = tblString + "</tbody>";
	 	tblString = tblString +  "</table>";				
 	 	
 	container.innerHTML = tblString;
 
 
 	}
 	 	
 	 /*	
 	 function displayExemTabHeader(definition) {
 	 	eval( "var deff = " + definition);
 	 	
 	 	tblString = "<thead><tr>" +	
 	 	for (var i=0; i<deff.length; i++){
			tblString = tblString + "<th width=\"" + deff[i][0] + "\" class=\"\"> " + deff[i][1] + "</th>"
 	 	}
 	 	tblString = "</tr></thead>" ;
			
 	 }*/
 	
function displayMono(container, exemplarTable) { 	
 	
 	var i=0;
 		var j=0;
 		var tblString = "";
		tblString = "<table id=\"exemplars\" class=\"exemdata\">";
	
		
		tblString = tblString + "<thead><tr>" +
				"<th width=\"80\" class=\"\">Signatura</th>" +
				"<th width=\"80\" class=\"\">Místo uložení</th>" +
				"<th width=\"80\" class=\"\">Přír. číslo</th>" +
				"<th width=\"100\" class=\"\">Externí uživatel</th>" +
				"<th width=\"100\" class=\"\">Interní uživatel</th>" +
				"<th width=\"100\" class=\"\">Stav</th>"+
				"<th width=\"120\" class=\"\">Rezervace</th></tr></thead>" ;
			
		tblString = tblString + "<tbody>";
		exemplarTable.items.sort(sortCaseInsensitiveExem);
		
 		for (i=0; i<exemplarTable.items.length; i++){
 					tblString = tblString + "<tr>" +	
 					"<td>" + exemplarTable.items[i].mark + "</td>" + 
 					"<td>" + exemplarTable.items[i].storage + "</td>" + 	
					"<td>" + exemplarTable.items[i].acq_no + "</td>" + 
 					"<td>" + exemplarTable.items[i].extloantype + "</td>" +	
 					"<td>" + exemplarTable.items[i].intloantype + "</td>" +	
 					"<td>" + exemplarTable.items[i].status + "</td>" + 	
 					"<td><a href=\"/" + E_URL + "/main?ReadForm&op=cr&pid=" + exemplarTable.items[i].pid + "\"> Rezervovat </a></td>";
 					 tblString = tblString + "</tr>";
 		}
 		tblString = tblString + "</tbody>";
	 	tblString = tblString +  "</table>";				
 	
 	
 	container.innerHTML = tblString;	
 	
}
function sortCaseInsensitiveVol(a,b) {
		//var that = jsonTable.that;
		
		var aa = (a["volume"]).toLowerCase();
		var bb = (b["volume"]).toLowerCase();
		var aai = aa.lastIndexOf('/');
		var bbi = bb.lastIndexOf('/');
		
		if (aai != -1) {
			aa = aa.substring(aai+1);
		}
		
		if (bbi != -1) {
			bb = bb.substring(bbi+1);
		}
		
		if (aa==bb) {
			return 0;
		} else if (aa<bb) {
			return -1;
		} else {
			return 1;
		}
	}
function sortCaseInsensitiveExem(a,b) {
		//var that = jsonTable.that;
		
		var aa = (a["mark"]).toLowerCase();
		var bb = (b["mark"]).toLowerCase();
		if (aa==bb) {
			return 0;
		} else if (aa<bb) {
			return -1;
		} else {
			return 1;
		}
	}
	
function sortCaseInsensitiveIssue(a,b) {
		//var that = jsonTable.that;
		
		var aa = parseFloat(a["issue"]);
		var bb = parseFloat(b["issue"]);
		
		if (isNaN(aa)) { 
			aa = 0;
		}
		
		if (isNaN(bb)) { 
			bb = 0;
		}
		return aa-bb;
	}
