/*----------------------------------------------------------------------------\
|                            Sortable Table 1.12                              |
|-----------------------------------------------------------------------------|
|                         Created by Erik Arvidsson                           |
|                  (http://webfx.eae.net/contact.html#erik)                   |
|                      For WebFX (http://webfx.eae.net/)                      |
|-----------------------------------------------------------------------------|
| A DOM 1 based script that allows an ordinary HTML table to be sortable.     |
|-----------------------------------------------------------------------------|
|                  Copyright (c) 1998 - 2004 Erik Arvidsson                   |
\----------------------------------------------------------------------------*/


var query2report_filter_objRef;
var query2report_filter_width = 440;

function getCheckBoxValue (oRow, nColumn) {
	return oRow.cells[nColumn].firstChild.checked ? 1 : 0;
};

function q2r_filter_inittable() {
//window.alert(document.getElementById("filterbuttons").getElementsByTagName("table")[0].id);
var elem = document.getElementById("filterbuttons").getElementsByTagName("table")[0];

var st_f = new SortableTable(elem, 0, false, false, ["CheckBox", "String"]);
st_f.addSortType("CheckBox", null, null, getCheckBoxValue);
	if (/MSIE/.test(navigator.userAgent)) {
		// backup check box values
		st_f.onbeforesort = function () {
			var table = st_f.element;
			var inputs = table.getElementsByTagName("INPUT");
			var l = inputs.length;
			for (var i = 0; i < l; i++) {
				inputs[i].parentNode.parentNode._checked = inputs[i].checked;
			}
		};
		// restore check box values
		st_f.onsort = function () {
			var rows = st_f.tBody.rows;
			var table = st_f.element;
			var inputs = table.getElementsByTagName("INPUT");
			var l = inputs.length;
			
			for (var i = 0; i < rows.length; i++) {
				removeClassName(rows[i], i % 2 ? "filter_odd" : "filter_even");
				addClassName(rows[i], i % 2 ? "filter_even" : "filter_odd");
			}
			for (var i = 0; i < l; i++) {
				inputs[i].checked = inputs[i].parentNode.parentNode._checked;
			}
		};
	} else {
		st_f.onsort = function () {
			var rows = st_f.tBody.rows;
			var l = rows.length;
			for (var i = 0; i < l; i++) {
				removeClassName(rows[i], i % 2 ? "filter_odd" : "filter_even");
				addClassName(rows[i], i % 2 ? "filter_even" : "filter_odd");
			}
		};
	}
}

document.oncontextmenu = new Function("if (query2report_rclickonth==true) { query2report_rclickonth = false; return false; } else {query2report_clearFilters(); return true; }");
document.onclick = new Function("e", "if (query2report_rclickonth!=true) query2report_clearFilters(1,e); return true;");

function filterdiv_revealall() { //selects all filter checkboxes
	var fdiv = document.getElementById("filterdiv");
	var inputs = fdiv.getElementsByTagName("input");
	for(var i = 0; i<inputs.length; i++)
		if(inputs[i].type=="checkbox") {
			if(query2report_isInt(inputs[i].name.substr(1))) {
				inputs[i].checked = true;				
			}			
		}
}

function filterdiv_hideall() { //deselects all filter checkboxes
	var fdiv = document.getElementById("filterdiv");
	var inputs = fdiv.getElementsByTagName("input");
	for(var i = 0; i<inputs.length; i++)
		if(inputs[i].type=="checkbox") {
			if(query2report_isInt(inputs[i].name.substr(1))) {
				inputs[i].checked = false;				
			}			
		}
}

function filterdiv_invert() { //inverts checkbox selection
	var fdiv = document.getElementById("filterdiv");
	var inputs = fdiv.getElementsByTagName("input");
	for(var i = 0; i<inputs.length; i++)
		if(inputs[i].type=="checkbox") {
			if(query2report_isInt(inputs[i].name.substr(1))) {
				inputs[i].checked = !inputs[i].checked;				
			}			
		}
}

function filterdiv_expand() {
	if(document.getElementById) {
		var fb = document.getElementById("filterbuttons");
		var fdiv = document.getElementById("filterdiv");
		var fiframe = document.getElementById("filteriframe");
		if(fb.style.height == "auto") {
		var ftableheight = document.getElementById("filtertable").offsetHeight;
			if(ftableheight>160) {
				fb.style.height = "170";
//				if (navigator.appName != "Microsoft Internet Explorer")				
					fdiv.style.height = "200";
					fiframe.style.height = "200";
			} else {
				fb.style.height = ftableheight;
//				if (navigator.appName != "Microsoft Internet Explorer")
					fdiv.style.height = ftableheight+30;
					fiframe.style.height = ftableheight+30;
			}
			document.getElementById("fdiv_expandbutton").value = arr_q2rGlobalization['Expand'];
		} else {
			fb.style.height = "auto";
//			if (navigator.appName != "Microsoft Internet Explorer")			
				fdiv.style.height = fb.offsetHeight + 30;			
				fiframe.style.height = fb.offsetHeight + 30;
			document.getElementById("fdiv_expandbutton").value = arr_q2rGlobalization['Collapse'];			
		}
	}	
}

function query2report_isInt(value) {
	if (isNaN(value))
		return false;
	else {
		if ((value * 1) < 0)
			return false;
		if (value.indexOf('.') > -1)
		  	return false;
	}
	return true;
}

function query2report_clearFilters(conditional,e) {
	if(conditional==1) {
		if(document.getElementById) {
				if(document.getElementById("filterdiv")&&document.getElementById("filterbuttons")) {
					var l = parseInt(document.getElementById("filterdiv").style.left);
					var t = parseInt(document.getElementById("filterdiv").style.top);
					var w = parseInt(document.getElementById("filterdiv").style.width);
					var h = parseInt(document.getElementById("filterdiv").style.height);
					
					w = parseInt(document.getElementById("filterbuttons").style.width);
					h = parseInt(document.getElementById("filterbuttons").offsetHeight) + 30;
					
		
							
					var mousex = (typeof e == "object")?parseInt(e.pageX):parseInt(window.event.clientX)+parseInt(document.body.scrollLeft);
					var mousey = (typeof e == "object")?parseInt(e.pageY):parseInt(window.event.clientY)+parseInt(document.body.scrollTop);
		
		//			window.alert("WIDTH: "+w+" HEIGHT: "+h+" MOUSEX: "+mousex+" MOUSEY: "+mousey);
					
					if(!(mousex>l && mousex<(l+w) && mousey>t && mousey<(t+h))) {
						if(document.getElementById("filteriframe") && document.getElementById("filterdiv")) {
							document.getElementById("filteriframe").style.display = "none";			
							document.getElementById("filterdiv").style.visibility = "hidden";
						}
					}
				}

			
		}
		else
			document.filterdiv.visibility = "hide";
	} else {
		if(document.getElementById) {
			if(document.getElementById("filteriframe") && document.getElementById("filterdiv")) {
				document.getElementById("filteriframe").style.display = "none";		
				document.getElementById("filterdiv").style.visibility = "hidden";
			}
		} else
			document.filterdiv.visibility = "hide";
	}	
}



function SortableTable(oTable, _reportCounter, _flagShowRecordsCount, _flagFilterable, oSortTypes) {

	this.sortTypes = oSortTypes || [];
	
	this.reportCounter = _reportCounter;
	
	this.sortColumn = null;
	this.descending = null;

	var oThis = this;
	this._headerOnclick = function (e) {
		oThis.headerOnclick(e);
	};
	
	this._headerOnMousedown = function(e) {
		oThis.headerOnMousedown(e);
	};

	if (oTable) {
		this.setTable( oTable );
		this.document = oTable.ownerDocument || oTable.document;
	}
	else {
		this.document = document;
	}

	this.filterCache = [];
	this.checkedBoxes = []; //list of checked CB's after a filter is applied
	this.hiddenRows = []; //the visible rows for each column
	
	this.flagShowRecordsCount = (_flagShowRecordsCount.toString().toLowerCase() == "true")?true:false;
	this.filterable = (_flagFilterable.toString().toLowerCase() == "true")?true:false;
	
	// only IE needs this
	var win = this.document.defaultView || this.document.parentWindow;

	this._onunload = function () {
		oThis.destroy();
	};
	if (win && typeof win.attachEvent != "undefined") {
		win.attachEvent("onunload", this._onunload);
	}
}

SortableTable.gecko = navigator.product == "Gecko";
SortableTable.msie = /msie/i.test(navigator.userAgent);
// Mozilla is faster when doing the DOM manipulations on
// an orphaned element. MSIE is not
SortableTable.removeBeforeSort = SortableTable.gecko;

SortableTable.prototype.onsort = function () {};

// default sort order. true -> descending, false -> ascending
SortableTable.prototype.defaultDescending = false;

// shared between all instances. This is intentional to allow external files
// to modify the prototype
SortableTable.prototype._sortTypeInfo = {};

SortableTable.prototype.setTable = function (oTable) {
	if ( this.tHead )
		this.uninitHeader();
	this.element = oTable;
	this.setTHead( oTable.tHead );
	this.setTBody( oTable.tBodies[0] );
};

SortableTable.prototype.setTHead = function (oTHead) {
	if (this.tHead && this.tHead != oTHead )
		this.uninitHeader();
	this.tHead = oTHead;
	this.initHeader( this.sortTypes );
};

SortableTable.prototype.setTBody = function (oTBody) {
	this.tBody = oTBody;
};

SortableTable.prototype.setSortTypes = function ( oSortTypes ) {
	if ( this.tHead )
		this.uninitHeader();
	this.sortTypes = oSortTypes || [];
	if ( this.tHead )
		this.initHeader( this.sortTypes );
};

// adds arrow containers and events
// also binds sort type to the header cells so that reordering columns does
// not break the sort types

SortableTable.prototype.initHeader = function (oSortTypes) {
	if (!this.tHead) return;
	var cells = this.tHead.rows[0].cells;
	var doc = this.tHead.ownerDocument || this.tHead.document;
	this.sortTypes = oSortTypes || [];
	var l = cells.length;
	var img, c;
	for (var i = 0; i < l; i++) {
		c = cells[i];
		if (this.sortTypes[i] != null && this.sortTypes[i] != "None") {
			img = doc.createElement("IMG");
			img.src = "/images/icons/q2r/blank.png";
			img2 = doc.createElement("IMG");
			img2.src = "/images/icons/q2r/blank.png";			
			///
			img.style.width = "0px";
			img.style.height = "11px";
			img2.style.width = "0px";
			img2.style.height = "12px";
					
			c.appendChild(img);
			c.insertBefore(img2, c.firstChild);
						
			if (this.sortTypes[i] != null)
				c._sortType = this.sortTypes[i];
			if (typeof c.addEventListener != "undefined") {
				c.addEventListener("click", this._headerOnclick, false);
				c.addEventListener("mousedown", this._headerOnMousedown, false);				
			} else if (typeof c.attachEvent != "undefined") {
				c.attachEvent("onclick", this._headerOnclick);
				c.attachEvent("onmousedown", this._headerOnMousedown);				
			} else {
				c.onclick = this._headerOnclick;
				c.onmousedown = this._headerOnMousedown;
			}
		}
		else
		{
			c.setAttribute( "_sortType", oSortTypes[i] );
			c._sortType = "None";
		}
	}
	this.updateHeaderArrows();
};

// remove arrows and events
SortableTable.prototype.uninitHeader = function () {
	if (!this.tHead) return;
	var cells = this.tHead.rows[0].cells;
    if(typeof cells != 'undefined' && cells!=null) {	
	    var l = cells.length;
	    var c;
	    for (var i = 0; i < l; i++) {
		    c = cells[i];
		    if (c._sortType != null && c._sortType != "None") {
			    c.removeChild(c.lastChild);
			    if (typeof c.removeEventListener != "undefined") {
				    c.removeEventListener("click", this._headerOnclick, false);
				    c.removeEventListener("mouseup", this._headerOnMousedown, false);
			    } else if (typeof c.detachEvent != "undefined") {
				    c.detachEvent("onclick", this._headerOnclick);
				    c.detachEvent("onmouseup", this._headerOnMousedown);
			    }
			    c._sortType = null;
			    c.removeAttribute( "_sortType" );
		    }
	    }
	 }
};

SortableTable.prototype.FilterImageInThead = function(nColumn, flag) {
	if (!this.tHead) return;nColumn
	var cells = this.tHead.rows[0].cells;
	
	var img;
	img = cells[nColumn].firstChild;
	
	if(flag==1) {
		img.className = "filter-img on";// + (this.descending ? "descending" : "ascending");
		img.style.width = "12px";
		img.style.height = "12px";
		addClassName(cells[nColumn], "filtered_thead_td");
//		window.alert(cells[nColumn].outerHTML);
//		cells[nColumn].outerHTML = cells[nColumn].outerHTML.replace('<TD ', '<TD STYLE="background:#ffffff" ');
	} else {
		img.className = "filter-img off";// + (this.descending ? "descending" : "ascending");
		img.style.width = "0px";
		removeClassName(cells[nColumn], "filtered_thead_td");
	}
};

SortableTable.prototype.updateHeaderArrows = function () {
	if (!this.tHead) return;
	var cells = this.tHead.rows[0].cells;
	var l = cells.length;
	var img;
	for (var i = 0; i < l; i++) {
		if (cells[i]._sortType != null && cells[i]._sortType != "None") {
			img = cells[i].lastChild;
			if (i == this.sortColumn) {
				img.className = "sort-arrow " + (this.descending ? "descending" : "ascending");
				///
				img.style.width = "";
			} else {
				img.className = "sort-arrow";
				///
				img.style.width = "0px";
			}
		}
	}
};

SortableTable.prototype.headerOnclick = function (e) {
	// find TD element
	var el = e.target || e.srcElement;
	while (el.tagName != "TD")
		el = el.parentNode;
	this.sort(SortableTable.msie ? SortableTable.getCellIndex(el) : el.cellIndex);
};

SortableTable.prototype.filter_setVisibleRecordsCount = function(num) {
	if(this.flagShowRecordsCount == true) {
		var el = this.tHead.parentNode;
		var i = 0;
		var pos = 0;
		var pos2 = 0;
		var pos3 = 0;
		while(el.tagName != "SPAN" && el.tagName!="BR") {
			if(el.previousSibling.tagName == "BR")
				return;
			el = el.previousSibling;
		}

		var str = el.innerHTML;
		
		var el2 = document.getElementById('currnumofrecs');
		var str2 = el2.innerHTML;
		
		var el3 = document.getElementById('totalrecords');
		if(el3)
			var str3 = el3.innerHTML;
		
		pos2 = str2.indexOf(" / ");
		
		if(pos2 == -1) { //no filter applied by now
//			window.alert(str.substr(22).charAt(0));
			//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//			if(str.substr(22).charAt(0)=='[')  { // no paging

			if(str.indexOf('[')==-1) { // no paging
				var total = parseInt(str2);
				if (num < total) {
//					el2.innerHTML = num + " / <span id=\"total_recs\">" + total + "</span></b>";
					el2.innerHTML = num + ' / ' + total;
				}					
		   } else {
			   	
				var total_page = parseInt(str2);
				
//				alert(total_page);
				
//				window.alert(str.substr(24+parseInt(total_page.toString().length)).charAt(0));
				var total = parseInt(str3);
//				alert('num is ' + num + '\n total is ' + total);
				
				if (num<total) {
					el2.innerHTML = num + ' / ' + total_page;
					el3.innerHTML = total;
				}				
		   }
		} else { //filter already applied
/*
			str = el.innerHTML;
			pos = str.indexOf('total_recs');
			pos = str.indexOf(">", pos);
			pos2 = str.indexOf("</", pos);
			var total = parseInt(str.substr(pos+1, pos2-pos-1));
*/
			
			var total = parseInt(str2.substr(pos2+3));
			
//			alert('str2 is ' + str2 + '\npos2 is ' + pos2 + '\nsubstr is ' + str2.substr(pos2));
//			alert('total is ' + total);

			if(str.indexOf("[") == -1) { // no paging
				if(num<total) {
//					el2.innerHTML = num + " / <span id=\"total_recs\">"+total+"</span>";
					el2.innerHTML = num + ' / ' + total;
					//el.innerHTML = "<b><span id=\"numofrecscaption\">Number of Records:</span> "+num+" / <span id=\"total_recs\">"+total+"</span>"+"</b>";
				} else if (num==total) {
					el2.innerHTML = total;
					//el.innerHTML = "<b><span id=\"numofrecscaption\">Number of Records:</span> "+total+"</b>";
				}
			 } else {
/*
				pos = str.indexOf('total_page');
				pos = str.indexOf(">", pos);
				pos2 = str.indexOf("</", pos);
				var total_page = parseInt(str.substr(pos+1, pos2-pos-1));
*/
				var total_page = parseInt(str3);
				
				if(num < total_page) {
					//el.innerHTML = "<b><span id=\"numofrecscaption\">Number of Records: "+num+" / <span id=\"total_page\">"+total_page+"</span> [<span id=\"total_recs\">"+total+"</span> total]"+"</b>";
					//el2.innerHTML = num+" / <span id=\"total_page\">"+total_page+"</span>";
					el2.innerHTML = num + ' / ' + total_page;
					el3.innerHTML = total;
				} else if (num == total_page) {
					el2.innerHTML = num;
					el3.innerHTML = total;
					//"<b><span id=\"numofrecscaption\">Number of Records: "+num+" ["+total+" total]</b>";
				}				 
			 }
		}
//		window.alert(el.innerHTML);
	}
};


SortableTable.prototype.doFilter = function(nColumn) { // r2kv = rows to keep visible; r2h = rows to hide
//window.alert("r2kv: "+r2kv+" || r2h: "+r2h);
	var fdiv = document.getElementById("filterdiv");
	var inputs = fdiv.getElementsByTagName("input");
	var inputs2;
	var index;
	var cntVisible = 0;
	var value;
	var rowsToKeepVisible = "";
	var rowsToHide = "";
	var rowNumber = 0;
	var j = 0;
//	var checkedCBs = "";
	var hiddenByOtherFilters = "";
	var areThereHiddenFields = false;
	
	for(var i = 0; i<this.hiddenRows.length; i++)
		if(i!=nColumn)
			hiddenByOtherFilters += this.hiddenRows[i];
	hiddenByOtherFilters += ":";			


	for(i = 0; i<inputs.length; i++) {
		if(inputs[i].type=="checkbox") {
			if(query2report_isInt(inputs[i].name.substr(1))) {
				if(inputs[i].checked == true) { //leaveRowVisible
					index = parseInt(inputs[i].name.substr(1));
					rowsToKeepVisible += inputs["hid_filter"+index].value;//eval("document.getElementById('hid_filter"+index+"').value");
				} else {
					index = parseInt(inputs[i].name.substr(1));
					rowsToHide += inputs["hid_filter"+index].value; // eval("document.getElementById('hid_filter"+index+"').value");
					areThereHiddenFields = true;
				}
			j++;
			}
		}
	}
/*	
	if(r2kv!=-1& r2h!=-1) {
		rowsToKeepVisible = r2kv;
		rowsToHide = r2h;
	}
	if(r2h!=-1&&r2h!=":")
		areThereHiddenFields = true;
*/		
	if(areThereHiddenFields)
		this.FilterImageInThead(nColumn,1);
	else
		this.FilterImageInThead(nColumn,0);

	rowsToKeepVisible += ":";
//	window.alert("rows to keep visible: "+rowsToKeepVisible);
	rowsToHide += ":";
/*	
	if(rowsToHide!=':') {
		var elem = document.createElement('input');
		elem.type = "hidden";
		elem.name = "PCmsReportPageFilter_r2kv"+eval(parseInt(this.reportCounter)-1)+"_"+nColumn;
		elem.value = rowsToKeepVisible;
		window.document['PCmsReportForm'+eval(parseInt(this.reportCounter)-1)].appendChild(elem);
		var elem2 = document.createElement('input');
		elem2.type = "hidden";
		elem2.name = "PCmsReportPageFilter_r2h"+eval(parseInt(this.reportCounter)-1)+"_"+nColumn;
		elem2.value = rowsToHide;
		window.document['PCmsReportForm'+eval(parseInt(this.reportCounter)-1)].appendChild(elem2);
	}
*/
	
//	window.alert("rowsToKeepVisible: '"+rowsToKeepVisible+"' || rowsToHide '"+rowsToHide+"'");
	
	this.hiddenRows[nColumn] = rowsToHide;
	
	var displayValue = (document.all)?"block":"table-row";
	var rows = this.tBody.rows;

	for (var i = 0; i <  rows.length; i++)  {
	

		// ako redyt se filtrira ot tekushtata kolona ILI redyt e skrit ot filter v druga kolona
		
		if ((rowsToKeepVisible.indexOf(":"+i+":") == -1) || (hiddenByOtherFilters.indexOf(":"+i+":") != -1)) {
			inputs2 = rows[i].getElementsByTagName("input");
			for(var j = 0; j<inputs2.length; j++) {
				if(!inputs2[j].disabled)
					inputs2[j].setAttribute("disabledbyfilter","1");
					inputs2[j].disabled = "true";
			}
			
			rows[i].style.display = "none";
			
		} else { //redyt ne e skrit ot filter v tekushtata kolona ili v nqkoq druga kolona
			cntVisible++;
			inputs2 = rows[i].getElementsByTagName("input");
			//disable all inputs
			for(var j = 0; j<inputs2.length; j++) {
				if(inputs2[j].getAttribute("disabledbyfilter")!=null)
					if(inputs2[j].getAttribute("disabledbyfilter").toString() == "1") {
						inputs2[j].disabled = false;
					}
			}
			
			rows[i].style.display = displayValue;
			removeClassName(rows[i], rowNumber % 2 ? "reporttable_odd" : "reporttable_even");
			addClassName(rows[i], rowNumber % 2 ? "reporttable_even" : "reporttable_odd");
			rowNumber++;
		}

			//if(rows[i].getAttribute("filtered"))
			//	window.alert("BEFORE: "+rows[i].getAttribute("filtered"));
// ako se skriva ot tekushtata kolona dobavi tekushtata kolona kym atributa 'filtered' na tr-to 
if ((rowsToKeepVisible.indexOf(":"+i+":") == -1)) { //if not found then addAttribute

			if(!rows[i].getAttribute("filtered"))
				rows[i].setAttribute("filtered", ":"+nColumn+":");
			else {
				strFiltered = rows[i].getAttribute("filtered").toString();
				if(strFiltered.indexOf(":"+nColumn+":")==-1) {
					strFiltered += nColumn + ":";
					rows[i].setAttribute("filtered", strFiltered);					
				}
//				window.alert(strFiltered);


			}
	
	if(typeof parent.autoIframe == 'function')
		if(parent.document.getElementById('SmSnippetIframe_ClientSurveyExplorer'))
			parent.autoIframe('SmSnippetIframe_ClientSurveyExplorer');
}

if(rowsToKeepVisible.indexOf(":"+i+":") != -1) { //ako trqbva da byde pokazan ot tazi kolona
//			window.alert("row "+i+" is in rowsToKeepVisible["+rowsToKeepVisible+"]");
			if(rows[i].getAttribute("filtered")) { 
				strFiltered = rows[i].getAttribute("filtered").toString();

//				window.alert("!!strFiltered  '"+strFiltered+"' for row "+i);

				if(strFiltered.indexOf(":"+nColumn+":")!=-1) {
					strFiltered = strFiltered.replace(":"+nColumn+":",":");

					if(strFiltered.length!=0)
						rows[i].setAttribute("filtered", strFiltered);
					else
						rows[i].removeAttribute("filtered");
				}
			}
}
			//if(rows[i].getAttribute("filtered"))
			//	window.alert("AFTER: "+rows[i].getAttribute("filtered"));
	} //for
query2report_clearFilters(0,null);
this.filter_setVisibleRecordsCount(cntVisible);
};

var query2report_rclickonth = false;

SortableTable.prototype.headerOnMousedown = function (e) { //Filter popup control is here

		
		var fdiv = document.getElementById("filterdiv");
		var fiframe = document.getElementById("filteriframe");

if(this.filterable == true) {
		var el = e.target || e.srcElement;
		while (el.tagName != "TD")
			el = el.parentNode;
		
		query2report_filter_objRef = this;

		
		if (navigator.appName == "Microsoft Internet Explorer") {
			if(event.button == "2" || event.button == "3") {
				query2report_rclickonth = true;
				var strHtml = this.buildFilterHTML(this.getDistinct(null, SortableTable.msie ? SortableTable.getCellIndex(el) : el.cellIndex), SortableTable.msie ? SortableTable.getCellIndex(el) : el.cellIndex, el.innerText );
				//window.alert(strHtml);
                
                fdiv.innerHTML = strHtml;
                var fbuttons = document.getElementById("filterbuttons");
				q2r_filter_inittable();		

				var ftableheight = document.getElementById("filtertable").offsetHeight;

				if(ftableheight < 160) {
					fbuttons.style.height = ftableheight+10;
					fiframe.style.height = ftableheight+40;
					fdiv.style.height = ftableheight+40;
				} else {
					fbuttons.style.height = 170;
					fdiv.style.height = 200;		
					fiframe.style.height = 200;					
				}

				var shortleft = (query2report_filter_width + 60 + window.event.clientX)>document.body.offsetWidth ;
				var shortbottom = (parseInt(fdiv.style.height)+ 10 + window.event.clientY)>document.body.offsetHeight;
				
				var posleft = 10 + window.event.clientX + document.body.scrollLeft;
				var postop = 10 + window.event.clientY + document.body.scrollTop;
				
//				window.alert("posleft: "+posleft+" postop: "+postop);
				
				if(shortleft)
					posleft -= query2report_filter_width;
				if(shortbottom)
					postop -= (parseInt(fdiv.style.height) + 10);	
				fdiv.style.left = posleft;
				fdiv.style.top = postop;
				fiframe.style.left = posleft;			
				fiframe.style.top = postop;
				fiframe.style.display = "block";
				fdiv.style.visibility = "inherit";
				return false;
			} else {
				fiframe.style.display = "none";			
				fdiv.style.visibility = "hidden";
			}
		}
		if (document.layers || (document.getElementById && !document.all)) 
			  if (e.which == "2" || e.which == "3") {
				query2report_rclickonth = true;
				
				var strHtml = this.buildFilterHTML(this.getDistinct(null, SortableTable.msie ? SortableTable.getCellIndex(el) : el.cellIndex), SortableTable.msie ? SortableTable.getCellIndex(el) : el.cellIndex, el.innerHTML.replace(/<[^>]+>/g,"") );
				
				if(document.getElementById) {
					fdiv.innerHTML = strHtml;
					var fbuttons = document.getElementById("filterbuttons");
					q2r_filter_inittable();	
				   
				    var ftableheight = document.getElementById("filtertable").offsetHeight;
				
				    if(ftableheight < 160) {
					    fbuttons.style.height = ftableheight+30;
					    fiframe.style.height = ftableheight+30;
					    fdiv.style.height = ftableheight+30;
				    } else {
					    fbuttons.style.height = 170;
					    fdiv.style.height = 200;		
					    fiframe.style.height = 200;					
				    }
				
					var posleft = 10 + e.pageX;
					var postop = 10 + e.pageY;
					
					//window.alert("posleft: "+posleft+" postop: "+postop);
					var shortleft = (posleft+query2report_filter_width + 20)>window.innerWidth+window.pageXOffset;
					var shortbottom = (postop+parseInt(fdiv.style.height) + 10)>window.innerHeight+window.pageYOffset;
					
//					window.alert("postop: "+postop+" fdiv.style.height"+ parseInt(fdiv.style.height)+" window.innerHeight: "+window.innerHeight+" window.pageYOffset: "+window.pageYOffset);
//				    window.alert("shortleft: "+shortleft+" shortbottom: "+shortbottom);
					
					if(shortleft)
						posleft -= query2report_filter_width;
					if(shortbottom)
						postop -= (parseInt(fdiv.style.height)+10);				
								
					
					fdiv.style.left = posleft;// + window.pageXOffset;
					fdiv.style.top = postop;// + window.pageYOffset;
					fdiv.style.visibility = "inherit";
				} else {
					document.filterdiv.innerHTML = strHtml;
					document.filterdiv.left = 10 + e.pageX;;
					document.filterdiv.top = 10 + e.pageY;
					document.filterdiv.visibility = "inherit";
				}
				return false;		
			}
	}// if(filterable)
};

// IE returns wrong cellIndex when columns are hidden
SortableTable.getCellIndex = function (oTd) {
	var cells = oTd.parentNode.childNodes
	var l = cells.length;
	var i;
	for (i = 0; cells[i] != oTd && i < l; i++)
		;
	return i;
};

SortableTable.prototype.getSortType = function (nColumn) {
	return this.sortTypes[nColumn] || "String";
};

// only nColumn is required
// if bDescending is left out the old value is taken into account
// if sSortType is left out the sort type is found from the sortTypes array

SortableTable.prototype.sort = function (nColumn, bDescending, sSortType) {
	if (!this.tBody) return;
	if (sSortType == null)
		sSortType = this.getSortType(nColumn);
	// exit if None
	if (sSortType == "None")
		return;

	if (bDescending == null) {
		if (this.sortColumn != nColumn)
			this.descending = this.defaultDescending;
		else
			this.descending = !this.descending;
	}
	else
		this.descending = bDescending;
	this.sortColumn = nColumn;

	if (typeof this.onbeforesort == "function")
		this.onbeforesort();

	var f = this.getSortFunction(sSortType, nColumn);
	var a = this.getCache(sSortType, nColumn);
	var tBody = this.tBody;
	a.sort(f);

	if (this.descending)
		a.reverse();

	if (SortableTable.removeBeforeSort) {
		// remove from doc
		var nextSibling = tBody.nextSibling;
		var p = tBody.parentNode;
		p.removeChild(tBody);
	}

	// insert in the new order
	var l = a.length;
	for (var i = 0; i < l; i++)
		tBody.appendChild(a[i].element);

	if (SortableTable.removeBeforeSort) {
		// insert into doc
		p.insertBefore(tBody, nextSibling);
	}

	this.updateHeaderArrows();

	this.destroyCache(a);

	if (typeof this.onsort == "function")
		this.onsort();
};

SortableTable.prototype.asyncSort = function (nColumn, bDescending, sSortType) {
	var oThis = this;
	this._asyncsort = function () {
		oThis.sort(nColumn, bDescending, sSortType);
	};
	window.setTimeout(this._asyncsort, 1);
};

/// FILTER:: get the DISTINCT values from a row
SortableTable.prototype.getDistinct = function(sType, nColumn) {

	if (sType == null)
		sType = this.getSortType(nColumn);

//!Caching shouldn't be used any more!			
//	if (typeof this.filterCache[nColumn] != "undefined") { //using cache
//		return (this.filterCache[nColumn]);
//	}
	
	if (!this.tBody)
		return [];
	
	var values = new Object();
	var rows = this.tBody.rows;
	var hrows = this.tHead.rows;
	var l = rows.length;
	var checkedCBs = ":";
	
	var headtds = hrows[0].getElementsByTagName("td");
	
//	window.alert(headtds[nColumn].className);
	
	for (var i = 0; i < l; i++)  {
		
//		window.alert("row "+i+ " display: "+rows[i].style.display);

		//ako redyt e skrit ot filtyr, prilojen v tazi kolona, to checkboxa mu trqbva da e unchecknat
		
		if(rows[i].getAttribute("filtered")) {
				strFiltered = rows[i].getAttribute("filtered").toString();
//				window.alert("STR FILTERED: "+strFiltered+" for row "+i+"\nnColumn: "+nColumn);
				if(strFiltered.indexOf(":"+nColumn+":")==-1)
					checkedCBs += i + ":";
		} else
			checkedCBs += i + ":";

///	window.alert("DEBUG: checkedCBs"+checkedCBs);
		
	
/*		
		if(rows[i].style.display!="none")
			checkedCBs += i + ":";
*/
//		else
//		 	if(headtds[nColumn].className.indexOf('filtered_thead_td')==-1)
//				checkedCBs += i + ":";

		if(typeof values[this.getRowFullValue(rows[i], sType, nColumn)] == "undefined")
			values[this.getRowFullValue(rows[i], sType, nColumn)] = ":"+i;
		else
			values[this.getRowFullValue(rows[i], sType, nColumn)] += ":"+i;
			
		
	}
//	window.alert("DEBUG: checkedCBs"+checkedCBs);
//	window.alert(checkedCBs);
//	for (val in values)
//		window.alert("values["+val+"]: "+values[val]);
	
	
	this.checkedBoxes[nColumn] = checkedCBs;	
	this.filterCache[nColumn] = values;
	return values;
};

/// FILTER:: build the HTML for the popup div

SortableTable.prototype.buildFilterHTML = function(oDistinct, nColumn, strFilteredVal) {
	var i = 0;
	var state = "";
	var sbHTML = new StringBuilder();
//	var func = new Function("nColumn", "this.doFilter(nColumn)");
	sbHTML.append('<div style="white-space:nowrap;">');
	sbHTML.append('<input type="button" style="font-size:8px; margin-left:4px; width:84px; text-decoration: none; 	font: Icon; border: 1px solid #8A867A; background-color: #F5F5F5; padding-left:5; padding-right:5; padding-top:0; padding-bottom:0; color:#000000; white-space:nowrap" value="' + arr_q2rGlobalization['Show All'] + '" title="' + arr_q2rGlobalization['Show All'] + '" onClick="filterdiv_revealall()">');	
	sbHTML.append('<input type="button" style="margin-left:2px; width:84px; text-decoration: none; 	font: Icon; border: 1px solid #8A867A; background-color: #F5F5F5; padding-left:5; padding-right:5; padding-top:0; padding-bottom:0; color:#000000; white-space:nowrap" value="' + arr_q2rGlobalization['Hide All'] + '" title="' + arr_q2rGlobalization['Hide All'] + '" onClick="filterdiv_hideall()">');	
	sbHTML.append('<input type="button" style="margin-left:2px; width:84px; text-decoration: none; 	font: Icon; border: 1px solid #8A867A; background-color: #F5F5F5; padding-left:5; padding-right:5; padding-top:0; padding-bottom:0; color:#000000; white-space:nowrap" value="' + arr_q2rGlobalization['Invert'] + '" title="' + arr_q2rGlobalization['Invert'] + '" onClick="filterdiv_invert()">');
	sbHTML.append('<input type="button" style="margin-left:2px; width:84px; text-decoration: none; 	font: Icon; border: 1px solid #8A867A; background-color: #F5F5F5; padding-left:5; padding-right:5; padding-top:0; padding-bottom:0; color:#000000; white-space:nowrap" value="' + arr_q2rGlobalization['Expand'] + '" title="' + arr_q2rGlobalization['Expand'] + '" id="fdiv_expandbutton" onClick="filterdiv_expand()">');
	sbHTML.append('<input type="button" style="margin-left:2px; margin-right:6px; width:84px;	text-decoration: none; 	font: Icon; border: 1px solid #8A867A; background-color: #F5F5F5; padding-left:5; padding-right:5; padding-top:0; padding-bottom:0; color:#000000; white-space:nowrap" value="' + arr_q2rGlobalization['Apply'] + '" title="' + arr_q2rGlobalization['Apply'] + '" onClick="query2report_filter_objRef.doFilter('+nColumn+');">');
	sbHTML.append('</div>');
	sbHTML.append('<div id="filterbuttons" style="width:438; height:170;position:inherit;overflow:auto; margin-top:5px">');	
	sbHTML.append("<table class=\"filtertable\" id=\"filtertable\" width=\"100%\" border=0 cellpadding=0 cellspacing=0>");
	sbHTML.append("<thead><tr style=\"padding-top:1px; padding-bottom:1px;\"><td>&nbsp;</td>")
    sbHTML.append("<td style=\"padding-left:4px;\" onMouseover=\"addClassName(this, 'reporttable_headerhover');\" onMouseout=\"removeClassName(this, 'reporttable_headerhover');\" title=\"Click to Sort / Right Click to Filter\">"+strFilteredVal+"</td></tr></thead><tbody>");
	
	var allCBs;
	var className;
	var flag = true;
	for (val in oDistinct) {
	var rwz = "";	
//		window.alert("oDistinct[val] : "+oDistinct[val]);
		
		if(typeof this.checkedBoxes[nColumn] != "undefined") {
		
			allCBs = oDistinct[val];//.split(":");
			allCBs = (allCBs.charAt(0)==':')?allCBs.substr(1):allCBs;
///			window.alert("allCBs is : "+allCBs);			
			allCBs = allCBs.split(":");
			
			for(var j = 0; j<allCBs.length; j++) {
			flag = true;
				rwz += allCBs[j]+'\n';
//				window.alert("row : "+allCBs[i]);
				if(this.checkedBoxes[nColumn].indexOf(":"+allCBs[j]+":")==-1) {
					flag = false;
					break;
				}
			}
			
///			window.alert(rwz);
			state = !flag?"":" checked ";
//			state = (this.checkedBoxes[nColumn].indexOf(":"+(i)+":")==-1)?"":" checked ";
//			window.alert(this.checkedBoxes[nColumn] + " and i is: "+i);
//			window.alert("val is: "+val);
		} else
			state = "checked";
			
		className = (i%2==0)?"filter_odd":"filter_even";	
		//<label for=\"c"+i+"\">
		sbHTML.append("<tr class="+className+" onMouseover=\"addClassName(this, 'reporttable_hover');\" onMouseout=\"removeClassName(this, 'reporttable_hover');\"><td style=\"font:Icon;\" width=\"1%\" valign=\"middle\"><input type=\"hidden\" name=\"hid_filter"+i+"\" value=\""+oDistinct[val]+"\"><input style=\"zoom:80%\" type=checkbox id=\"c"+(i)+"\" name=\"c"+(i)+"\" value=\"on\""+state+"></td><td style=\"font:Icon;\" width=\"99%\"><label style=\"cursor:hand;\" for=\"c"+(i++)+"\">"+val+"</label></td></tr>");

	}
	sbHTML.append("</tbody></table></div>");
	
	return sbHTML.toString();
};



SortableTable.prototype.getCache = function (sType, nColumn) {
	if (!this.tBody) return [];
	var rows = this.tBody.rows;
	var l = rows.length;
	var a = new Array(l);
	var r;
	for (var i = 0; i < l; i++) {
		r = rows[i];
		a[i] = {
			value:		this.getRowValue(r, sType, nColumn),
			element:	r
		};
	};
	return a;
};

SortableTable.prototype.destroyCache = function (oArray) {
	var l = oArray.length;
	for (var i = 0; i < l; i++) {
		oArray[i].value = null;
		oArray[i].element = null;
		oArray[i] = null;
	}
};

SortableTable.prototype.getRowValue = function (oRow, sType, nColumn) {
	// if we have defined a custom getRowValue use that
	if (this._sortTypeInfo[sType] && this._sortTypeInfo[sType].getRowValue)
		return this._sortTypeInfo[sType].getRowValue(oRow, nColumn);

	var s;
	var c = oRow.cells[nColumn];
	if (typeof c.innerText != "undefined")
		s = c.innerText;
	else
		s = SortableTable.getInnerText(c);
	return this.getValueFromString(s, sType);
};

SortableTable.prototype.getRowFullValue = function (oRow, sType, nColumn) { //needed by Filter
	if (this._sortTypeInfo[sType] && this._sortTypeInfo[sType].getRowValue)
		return this._sortTypeInfo[sType].getRowValue(oRow, nColumn);

	var s;
	var c = oRow.cells[nColumn];
	if (typeof c.innerHTML != "undefined") {
		var html = c.innerHTML;
		var pos1 = 0;
			pos1 = html.toLowerCase().indexOf("<p");
			if (pos1!=-1) {
				var pos2 = html.indexOf(">",pos1+1);
				html = html.substr(0, pos1) + html.substr(pos2+1);
				
				pos1 = html.toLowerCase().indexOf("</p>");
				if (pos1!=-1) {
					html = html.substr(0,pos1)+html.substr(pos1+4);
				}
			}
		//s = html;
		//remove hrefs
		var re = /href=[ ]*('|")([^"'])*('|")/;
		html = html.replace(re, "");
		//s = html;
			
		//remove onclicks		
		var re1 = /onclick=[ ]*"([^"\\"])*"/;
		var re2 = /onclick=[ ]*'([^'\\'])*'/;
		html = html.replace(re1, "");
		html = html.replace(re2, "");
		s = html;	

	}
	else
		s = SortableTable.getInnerText(c);
	return this.getValueFromString(s, sType);
};

SortableTable.getInnerText = function (oNode) {
	var s = "";
	var cs = oNode.childNodes;
	var l = cs.length;
	for (var i = 0; i < l; i++) {
		switch (cs[i].nodeType) {
			case 1: //ELEMENT_NODE
				s += SortableTable.getInnerText(cs[i]);
				break;
			case 3:	//TEXT_NODE
				s += cs[i].nodeValue;
				break;
		}
	}
	return s;
};

SortableTable.prototype.getValueFromString = function (sText, sType) {
	if (this._sortTypeInfo[sType])
		return this._sortTypeInfo[sType].getValueFromString( sText );
	return sText;
	/*
	switch (sType) {
		case "Number":
			return Number(sText);
		case "CaseInsensitiveString":
			return sText.toUpperCase();
		case "Date":
			var parts = sText.split("-");
			var d = new Date(0);
			d.setFullYear(parts[0]);
			d.setDate(parts[2]);
			d.setMonth(parts[1] - 1);
			return d.valueOf();
	}
	return sText;
	*/
	};

SortableTable.prototype.getSortFunction = function (sType, nColumn) {
	if (this._sortTypeInfo[sType])
		return this._sortTypeInfo[sType].compare;
	return SortableTable.basicCompare;
};

SortableTable.prototype.destroy = function () {
	this.uninitHeader();
	var win = this.document.parentWindow;
	if (win && typeof win.detachEvent != "undefined") {	// only IE needs this
		win.detachEvent("onunload", this._onunload);
	}
	this._onunload = null;
	this.element = null;
	this.tHead = null;
	this.tBody = null;
	this.document = null;
	this._headerOnclick = null;
	this._headerOnMousedown = null;	
	this.sortTypes = null;
	this._asyncsort = null;
	this.onsort = null;
};

// Adds a sort type to all instance of SortableTable
// sType : String - the identifier of the sort type
// fGetValueFromString : function ( s : string ) : T - A function that takes a
//    string and casts it to a desired format. If left out the string is just
//    returned
// fCompareFunction : function ( n1 : T, n2 : T ) : Number - A normal JS sort
//    compare function. Takes two values and compares them. If left out less than,
//    <, compare is used
// fGetRowValue : function( oRow : HTMLTRElement, nColumn : int ) : T - A function
//    that takes the row and the column index and returns the value used to compare.
//    If left out then the innerText is first taken for the cell and then the
//    fGetValueFromString is used to convert that string the desired value and type

SortableTable.prototype.addSortType = function (sType, fGetValueFromString, fCompareFunction, fGetRowValue) {
	this._sortTypeInfo[sType] = {
		type:				sType,
		getValueFromString:	fGetValueFromString || SortableTable.idFunction,
		compare:			fCompareFunction || SortableTable.basicCompare,
		getRowValue:		fGetRowValue
	};
};

// this removes the sort type from all instances of SortableTable
SortableTable.prototype.removeSortType = function (sType) {
	delete this._sortTypeInfo[sType];
};

SortableTable.basicCompare = function compare(n1, n2) {
	if (n1.value < n2.value)
		return -1;
	if (n2.value < n1.value)
		return 1;
	return 0;
};

SortableTable.idFunction = function (x) {
	return x;
};

SortableTable.toUpperCase = function (s) {
	return s.toUpperCase();
};

SortableTable.toDate = function (s) {
	var parts = s.split("-");
	var d = new Date(0);
	d.setFullYear(parts[0]);
	d.setDate(parts[2]);
	d.setMonth(parts[1] - 1);
	return d.valueOf();
};


// add sort types
SortableTable.prototype.addSortType("Number", Number);
SortableTable.prototype.addSortType("CaseInsensitiveString", SortableTable.toUpperCase);
SortableTable.prototype.addSortType("Date", SortableTable.toDate);
SortableTable.prototype.addSortType("String");
// None is a special case

/*----------------------------------------------------------------------------\
|                             String Builder 1.02                             |
|-----------------------------------------------------------------------------|
|                         Created by Erik Arvidsson                           |
|                  (http://webfx.eae.net/contact.html#erik)                   |
|                      For WebFX (http://webfx.eae.net/)                      |
|-----------------------------------------------------------------------------|
| A class that allows more efficient building of strings than concatenation.  |
|-----------------------------------------------------------------------------|
|                  Copyright (c) 1999 - 2002 Erik Arvidsson                   |
\----------------------------------------------------------------------------*/

 function StringBuilder(sString) {
	
	// public
	this.length = 0;
	
	this.append = function (sString) {
		// append argument
		this.length += (this._parts[this._current++] = String(sString)).length;
		
		// reset cache
		this._string = null;
		return this;
	};
	
	this.toString = function () {
		if (this._string != null)
			return this._string;
		
		var s = this._parts.join("");
		this._parts = [s];
		this._current = 1;
		this.length = s.length;
		
		return this._string = s;
	};

	// private
	this._current	= 0;
	this._parts		= [];
	this._string	= null;	// used to cache the string
	
	// init
	if (sString != null)
		this.append(sString);
}
// Thanks to Brian K. Cantwell for the initial code

function usCurrencyConverter( s )
{
	var n = s;
	var i = s.indexOf( "$" );
	if ( i == -1 )
		i = s.indexOf( "," );
	if ( i != -1 )
	{
		var p1 = s.substr( 0, i );
		var p2 = s.substr( i + 1, s.length );
		return usCurrencyConverter( p1 + p2 );
	}

	return parseFloat( n );
}

SortableTable.prototype.addSortType( "UsCurrency", usCurrencyConverter );

// Thanks to Bernhard Wagner for submitting this function

function replace8a8(str) {
	str = str.toUpperCase();
	var splitstr = "____";
	var ar = str.replace(
		/(([0-9]*\.)?[0-9]+([eE][-+]?[0-9]+)?)(.*)/,
	 "$1"+splitstr+"$4").split(splitstr);
	var num = Number(ar[0]).valueOf();
	var ml = ar[1].replace(/\s*([KMGB])\s*/, "$1");

	if (ml == "K")
		num *= 1024;
	else if(ml == "M")
		num *= 1024 * 1024;
	else if (ml == "G")
		num *= 1024 * 1024 * 1024;
	else if (ml == "T")
		num *= 1024 * 1024 * 1024 * 1024;
	// B and no prefix

	return num;
}

SortableTable.prototype.addSortType( "NumberK", replace8a8 );



function q2r_openPrint(el) {
	var tableStyle = '.reporttable {font:Icon;border:1px Solid ThreeDShadow;background:Window;color:WindowText;}.reporttable caption {font:Icon;font-weight:bold;padding:1px 5px;background:ButtonFace;border:1px solid;border-color:ButtonShadow ButtonShadow ButtonFace ButtonShadow;cursor:default;}.reporttable thead {font:Icon;background:ButtonFace;}.reporttable thead td {border:1px solid;border-color:ButtonHighlight ButtonShadow ButtonShadow ButtonHighlight;cursor:default;}.reporttable td {font:Icon;white-space:normal; padding:1px 5px;}.reporttable_even {background:#eee;}.reporttable_odd {}.reporttable_headerhover {cursor: pointer;border:  1px solid; border-color: #E8EAEF #0A246A #0A246A #E8EAEF; background: #B6BDD2; }.reporttable_hover {background: #D5DAE8;}.reporttable_arrow {font-family: Arial;font-weight:bold;font-size:7pt; text-align: center;letter-spacing: -1pt;} a img { border:0; }';
//Find the table
	do {
		el = el.nextSibling;
	} while (el.nodeName.toLowerCase() != "table");
//Found
	
//	window.alert(el.nodeName);
		
	var tableWidth = el.offsetWidth;
	tableWidth = tableWidth + 40;
	var tableHeight = el.offsetHeight;
	tableHeight = (tableHeight>440)?440:tableHeight+50;
	
	pwin=window.open("","pwin","width="+tableWidth+",height="+tableHeight+",toolbar=no,location=no,directories=no,status=no,menubar=yes,scrollbars=yes,resizable=yes");
	pwin.document.writeln('<html><head>');
	pwin.document.writeln('<title>Print table<\/title>');
	pwin.document.writeln('<style>\n'+tableStyle+'\n</style>\n');
	pwin.document.writeln('<script>function init() { var linx = document.getElementsByTagName("a"); for (var i =0; i<linx.length; i++) linx[i].href = ""; }</script>')
	pwin.document.writeln('<\/head><body onload="init();">');
	pwin.document.writeln('<div align="center">');
	//pwin.document.writeln('<a href="#"><font style="font:Icon;" onClick="print();">Click here to print<\/font><\/a><br><br>');
	pwin.document.writeln('<table class=reporttable id=reporttable cellSpacing=0>'+el.innerHTML+'</table>');
	pwin.document.writeln('<\/div>');
	pwin.document.write('<\/body><\/html>');
	pwin.document.writeln('<s' + 'cript>');
	pwin.document.writeln('function addClassName(a,b){}');
	pwin.document.writeln('function removeClassName(a,b){}');
	pwin.document.writeln('function sortColumn(a){}');
	pwin.document.writeln('<\/s' + 'cript>');
	pwin.document.close();
}

function addClassName(el, sClassName) {
	var s = el.className;
	var p = s.split(" ");
	var l = p.length;
	for (var i = 0; i < l; i++) {
		if (p[i] == sClassName)
			return;
	}
	p[p.length] = sClassName;
	el.className = p.join(" ");
			
}

function removeClassName(el, sClassName) {
	var s = el.className;
	var p = s.split(" ");
	var np = [];
	var l = p.length;
	var j = 0;
	for (var i = 0; i < l; i++) {
		if (p[i] != sClassName)
			np[j++] = p[i];
	}
	el.className = np.join(" ");
}

function PCmsReport_handlePageSizeInput(reportId, currPageNumber) {
	PCmsReportPageInpPageSize = eval("document.getElementById('PCmsReportPageInpPageSize"+reportId+"')").value;
	if(PCmsReportPageInpPageSize == "0")
		PCmsReportPageInpPageSize = "-1";
	if(query2report_isInt(PCmsReportPageInpPageSize)) {
//			reportform = window.document['PCmsReportForm'];
			document.getElementById("PCmsReportPagePageSize"+reportId).value = PCmsReportPageInpPageSize;
			PCmsReport_fixReportFormPageNumber(reportId, currPageNumber);
			PCmsReport_updatePatterns(reportId);
			window.document['PCmsReportForm'].submit();
	}
	return false;
}

function PCmsReport_handlePageSizeInputKeyPress(field,e) {
	var keycode;
	if (window.event)
		keycode = window.event.keyCode;
	else if (e)
		keycode = e.which;
	else
		return true;
	if (keycode == 13) {
		field.blur();	 
		return false;
	} else
		return true;
}

function PCmsReport_handlePageSizeSelect(reportId, currPageNumber) {
		var PCmsReportPageSelPageSize = document.getElementById("PCmsReportPageSelPageSize"+reportId);
		if (PCmsReportPageSelPageSize.options[PCmsReportPageSelPageSize.selectedIndex].value == "-1") { //custom
			selectDiv = document.getElementById("divPageSizeSelect"+reportId);
			inputDiv = document.getElementById("divPageSizeInput"+reportId);
			selectDiv.style.display = "none";
			inputDiv.style.display = "";
			document.getElementById("PCmsReportPageInpPageSize"+reportId).focus();
		} else if (PCmsReportPageSelPageSize.options[PCmsReportPageSelPageSize.selectedIndex].value > 0 && !isNaN(PCmsReportPageSelPageSize.options[PCmsReportPageSelPageSize.selectedIndex].value)) {
			pageSize = parseInt(PCmsReportPageSelPageSize.options[PCmsReportPageSelPageSize.selectedIndex].value);
			document.getElementById("PCmsReportPagePageSize"+reportId).value = pageSize;
/*	Thing breaks in CMS if action is set		
			pathName = window.location.pathname.replace("\\", "/");
			tmpArr = pathName.split("/");
			reportform.action = tmpArr[tmpArr.length-1];
*/
			PCmsReport_fixReportFormPageNumber(reportId, currPageNumber);
			PCmsReport_updatePatterns(reportId);
			window.document['PCmsReportForm'].submit();
		}
}

query2report_maxReports = 10;

function PCmsReport_updatePatterns(index) {
	window.document['PCmsReportForm'].PCmsReportPageSelPageSize.value = document.getElementById("PCmsReportPageSelPageSize"+index).value;
	window.document['PCmsReportForm'].PCmsReportPageInpPageSize.value = document.getElementById("PCmsReportPageInpPageSize"+index).value;
	
	var strNewPattern = "";
	arrPatterns = new Array();
	if(document.getElementById("PCmsReportPagePageSize"+index)) {
		pageSize = document.getElementById('PCmsReportPagePageSize'+index).value;
		var strPagingPattern = window.document['PCmsReportForm'].PCmsReportPage.value;
		tmpArr = strPagingPattern.split("I");
		for (j = 0; j < tmpArr.length; j++) {
				tmpArr2 = tmpArr[j].split("_");
				if(strNewPattern.length!=0)
						strNewPattern += "I";
				if(tmpArr2[0]==index) {
					if (query2report_isInt(pageSize) && pageSize.length>0)
						strNewPattern += tmpArr2[0] + "_" + tmpArr2[1] + "_" + pageSize;
					else
						strNewPattern += tmpArr2[0] + "_" + tmpArr2[1] + "_" + "10";
				} else {
					strNewPattern += tmpArr[j];
				}
		}
	}
//	window.alert("new pattern: "+strNewPattern);
//	window.alert(strNewPattern);
	document.getElementById("PCmsReportPagePagingPattern"+index).value = strNewPattern;
} //PCmsReport_updatePatterns

function PCmsReport_setReportFormValues(index, PCmsReportPage, PCmsReportPagePagingPattern, PCmsReportPagePageSize, PCmsReportPageSelPageSize, PCmsReportPageInpPageSize) {
	if (typeof eval("window.document['PCmsReportForm'].PCmsReportPagePagingPattern"+index) == 'undefined') 	{
		var elem = document.createElement('input');
		elem.type = "hidden";
		elem.name = "PCmsReportPagePagingPattern"+index;
		elem.id = "PCmsReportPagePagingPattern"+index;
		elem.value = PCmsReportPagePagingPattern;
		window.document['PCmsReportForm'].appendChild(elem);
	} else
		eval("window.document['PCmsReportForm'].PCmsReportPagePagingPattern"+index).value = PCmsReportPagePagingPattern;

	if (typeof eval("window.document['PCmsReportForm'].PCmsReportPagePageSize"+index) == 'undefined') 	{
		var elem = document.createElement('input');
		elem.type = "hidden";
		elem.name = "PCmsReportPagePageSize"+index;
		elem.id = "PCmsReportPagePageSize"+index;
		elem.value = PCmsReportPagePageSize;
		window.document['PCmsReportForm'].appendChild(elem);
	} else
		eval("window.document['PCmsReportForm'].PCmsReportPagePageSize"+index).value = PCmsReportPagePageSize;

	window.document['PCmsReportForm'].PCmsReportPageSelPageSize.value = PCmsReportPageSelPageSize;
	window.document['PCmsReportForm'].PCmsReportPageInpPageSize.value = PCmsReportPageInpPageSize;
} //PCmsReport_setReportFormValues

function PCmsReport_submitReportPage(index, pagenum) {
		PCmsReport_fixReportFormPageNumber(index, pagenum);
		PCmsReport_updatePatterns(index);			
//		dumpReportForm(index);
		window.document['PCmsReportForm'].submit();
} //PCmsReport_submitReportPage

function PCmsReport_fixReportFormPageNumber(index, pagenum) {
		window.document['PCmsReportForm'].PCmsReportPage.value = eval("window.document['PCmsReportForm'].PCmsReportPagePagingPattern"+index).value.replace("~~@!@OKJH%^PageNumberHere%^^OPKLK:!!]]!~^", pagenum);	
}

function dumpReportForm(index) {
	var str="";
	var inputs = window.document['PCmsReportForm'].getElementsByTagName('input');
	for(var i=0; i<inputs.length; i++)
		str += "\n"+inputs[i].name+" : "+inputs[i].value;
	window.alert(str);
}