1  /**
  2  * @fileOverview  This file provides basic client-side model of the Query-object. <code>Query</code> construction, 
  3  * manipulating and <code>queryset</code> model functionality. 
  4  *
  5  * @author 
  6  * @version 
  7  */
  8 
  9 var page_record_count = 10;
 10 var formatquerystring_len = 25;
 11 //var workspace;
 12 
 13 function Workspace(){
 14 
 15 };
 16 Workspace.save = function(type, query, id, iq){
 17 	var JSONText;
 18 	var qdata = "/";
 19 	/*
 20 	if (type == "ADMIN"){
 21 		JSONText = JSON.stringify(json_admin["WorkspaceProfile"]);
 22 	} else {
 23 		JSONText = JSON.stringify(jsonw["WorkspaceProfile"]);
 24 	}
 25 	*/
 26 	//var JSONText = JSON.stringify({"aa.a":"r"});
 27 	//notifyUser(JSONText,'debug');
 28 	
 29 	JSONText = JSON.stringify(jsonw["WorkspaceProfile"]);
 30 	if (query != undefined){
 31 		qdata = "/" + query.id;
 32 	} 
 33 	$.post("/MDService2/workspaceprofilesave/" + type + qdata,{"data":JSONText},  function(data) {
 34 		query.id = $(data).text();
 35 		jsonw["WorkspaceProfile"]["Querysets"][id]["Queries"][iq]["id"] = query.id;
 36 		appendQueryUI(jsonw["WorkspaceProfile"]["Querysets"][id]["Queries"][iq],iq, $('#userqueries'));
 37 //	      alert("success");
 38 	});
 39 	//.success(function() { alert("second success"); })
 40     //.error(function(e) { alert("error"); })
 41     //.complete(function() { alert("complete"); });
 42 
 43 
 44 };
 45 /*
 46 Workspace.newQueryID = function(){
 47 	var new_id;
 48 	
 49 	loadAdminFile();
 50 	json_admin["Admin"]["maxqid"]  = parseInt(json_admin["Admin"]["maxqid"]) + 1;
 51 	new_id = json_admin["Admin"]["maxqid"];
 52 	Workspace.save("ADMIN");
 53 	return new_id;
 54 };
 55 */
 56 function Collection(index, name){
 57 	this.index = index;
 58 	this.name = name;
 59 };
 60 //var collections  = [];
 61 
 62 /**
 63 Creates a new Query
 64 @class Represents a Query. 
 65 */ 
 66 function Query(collection, columns, query , squery) {
 67 	this.id = 0;
 68 	this.collection = collection;   // []
 69 	this.columns = columns;         // string
 70 	this.query = query;	         //sctext
 71 	this.squery = squery;
 72 	this.listid = "";
 73 	this.container = {};
 74 	// page
 75 	this.startItem = 1;
 76 	this.maximumItems = parseInt(this.startItem) + page_record_count - 1;
 77 	
 78 	// repository
 79 	this.repository = 1;
 80 	this.options = null;
 81 	this.time_created = null;
 82 	
 83 	this.format = 'htmltable';
 84 	this.columns_widget = null;
 85 };
 86 
 87 Query.prototype.load  = function(json) {
 88 	
 89 	var columns_text = "";
 90 	if (json.columns != "null"){
 91 		$.each(json.columns,function(i,item){
 92 			columns_text = columns_text + "," + item;
 93 		});
 94 		if (columns_text.length > 1) {
 95 			columns_text = columns_text.substring(1);	
 96 		}
 97 	}
 98 	this.columns = columns_text;
 99 	
100 	var collection = [];
101 	if (json.collections != "null"){
102 		$.each(json.collections,function(i,item){
103 			var coll = new Collection(item.index, item.name);
104 			collection[i] = coll;
105 		});
106 	}
107 	this.collection = collection;
108 	if (json["querystring"] == "[NULL]"){
109 		this.query = null;
110 	} else {
111 		this.query = json["querystring"];	
112 	}
113 	if (json["squerystring"] == "[NULL]"){
114 		this.squery = null;
115 	} else {
116 		this.squery = json["squerystring"];	
117 	}
118 	this.columns = columns_text;
119 	
120 	var options_text = "";
121 	if (json.options == undefined) {
122 		this.options = null;
123 	} else {
124 		if (json.options != "null"){
125 			$.each(json.options,function(i,item){
126 				options_text = options_text + "," + item;
127 			});
128 			if (options_text.length > 1) {
129 				options_text = options_text.substring(1);	
130 			}
131 			this.options = options_text;
132 		} else {
133 			this.options = null;
134 		}
135 	}
136 	
137 	if (json.time == undefined){
138 		this.time_created = null;
139 	} else {
140 		this.time_created = json.time;
141 	}
142 	this.id = json.id;
143 };
144 
145 Query.prototype.save = function(){
146 	//queryset id
147 	var id = parseInt($("#qts_select option:selected").val());
148 	var iq = 0;
149 	var queries = jsonw["WorkspaceProfile"]["Querysets"][id]["Queries"];
150 	
151 	//var iq = $('#userqueries').children().size();
152 	if (queries == "null"){
153 		jsonw["WorkspaceProfile"]["Querysets"][id]["Queries"] = [{}];
154 	} else {
155 		iq = queries.length;
156 	}
157 	// create queryID
158 	this.id = 0;//Workspace.newQueryID();//id + "_" + iq;
159 	var jsonq = this.toJSON();
160 	jsonw["WorkspaceProfile"]["Querysets"][id]["Queries"][iq] = jsonq;
161 	Workspace.save("USER", this, id, iq);
162 	//appendQueryUI(jsonw["WorkspaceProfile"]["Querysets"][id]["Queries"][iq],iq, $('#userqueries'));
163 	
164 };
165 
166 
167 Query.prototype.getcolumnstext = function (){
168 	
169 	if (this.columns_widget == null ) {
170 		return this.columns;
171 	}
172 	return this.columns_widget.getListText();
173 };
174 
175 Query.prototype.updatecolumnstext = function (list) {
176 	var columns_text = "";
177 	
178 	$(list).each(function(index){
179 		if (index > 0) {
180 			columns_text = columns_text + ",";
181 		}
182 		columns_text = columns_text + $(this).text();
183 	});
184 	this.columns = columns_text;
185 };
186 
187 /** special handling for special characters: double escaping (escape the %-sign)
188  * to survive the %-encoding through the request (and parsing) down to the transformation in XCQL2XPath.xsl
189  * it's: whitespace, and single and double-quotes (unified to double quotes %22)
190 */  
191 
192 Query.prototype.query_uri = function () {
193 	var params = "?";
194 	if (this.query != null) {
195 		params = params + "q=" + escape(this.query) + "&";
196 	}
197 	if (this.squery != null) {
198 		escaped_sq =escape(this.squery).replace(/%20/g,"%2520").replace(/\%2[27]/g,"%2522") ;
199 		escaped_sq = escaped_sq.replace(/%7C/g,"%257C").replace(/\+/g,"%2B"); 
200 		params = params + "squery=" + escaped_sq + "&";
201 	}
202 	params = params + "collection=" + this.getcollectiontext("index") + "&columns=" + this.getcolumnstext() + "&startItem=" + this.startItem + "&maximumItems=" + this.maximumItems + "&repository=" + this.repository;
203 	if  (this.options != null) {
204 		params = params + "&options=withSummary";
205 	}
206 	
207 	return params;
208 
209 	//return $.param(this.query);
210 };
211 
212 Query.prototype.sruquery_uri = function () {
213 	var params = "?operation=searchRetrieve&version=1.2&";
214 	var q = "";
215 	if (this.query != null) {
216 		q = "( "  + escape(this.query) + " )";
217 	}
218 	if (this.squery != null) {
219 		escaped_sq =escape(this.squery).replace(/%20/g,"%2520").replace(/\%2[27]/g,"%2522") ;
220 		escaped_sq = escaped_sq.replace(/%7C/g,"%257C").replace(/\+/g,"%2B"); 
221 		if (q.length > 0){
222 			q = q + " and ";
223 		}
224 		q = q + escaped_sq;
225 	}
226 	params = params + "query=" + q + "&x-cmd-collections=" + this.getcollectiontext("index") + 
227 	"&startRecord=" + this.startItem + "&maximumRecords=" + this.maximumItems + "&x-cmd-repository=" + this.repository;
228 	
229 	return params;
230 };
231 
232 Query.prototype.toString = function(){
233 	var str = "";
234 	var coll = (this.getcollectiontext("name") != "" ) ? " in " + this.getcollectiontext("name") : "";
235 	str = Query.queryliststring(this.squery, this.query) + coll + " @" + this.repository.toString();
236 	return str;
237 };
238 
239 Query.prototype.publish = function() {
240 	$.post("/MDService2/virtualcollection/USER/" + this.id,"");
241 };
242 
243 Query.prototype.toJSON = function () {
244 //Query.prototype.query_json = function () {	
245 	var dt = new Date();
246 	var str_time = dateFormat(dt);//dt.toString("dd/mm/yyyy HH:mm:ss");
247 	//var jsonq = { "options" : json_options, "bookmark" : bookmark, "time" : str_time};
248 	var json_options = this.options; 
249 	if (this.options != null) {
250 		json_opts = [{}];
251 		json_opts[0] = this.options;
252 	}
253 
254 	// collections
255 	var json_coll;
256 		
257 	if (this.collection.length == 0) {
258 		json_coll = {};
259 		json_coll = "null";
260 	} else { 
261 		json_coll = [{}];
262 		for (var i = 0; i < this.collection.length; i++) {
263 			json_coll[i] = {"index" : this.collection[i].index, "name" :this.collection[i].name};
264 		}
265 	}
266 	//columns
267 	var json_cols;
268 	var colls = this.columns;
269 	if (colls == "") {
270 		//json_cols = {};
271 		json_cols = "null";
272 	} else {  
273 		var pos = this.columns.indexOf(",", 0);
274 		var i = 0;
275 		
276 		json_cols = [{}];
277 		while (pos > -1){
278 			if (pos > -1){
279 				json_cols[i] = cols.substring(0,pos);
280 			} else {
281 				json_cols[i] = cols;
282 			}
283 			cols = cols.substring(pos+1);
284 			pos = cols.indexOf(",", 0);
285 			i = i+1;
286 		}
287 		
288 		json_cols[i] = cols;
289 	}
290 
291 	var jsonq = {"id":this.id,
292 				 "name":"",
293 			     "squerystring":this.squery, 
294 				 "querystring":this.query,	
295 				 "searchclauses":"null" ,
296 				 "collections" : json_coll, 
297 				 "columns" : json_cols,
298 				 "startItem" : this.startItem,
299 				 "maximumItems" : this.maximumItems,
300 				 "options" : json_options, 
301 				 "bookmark" : "0",
302 				 "time" : str_time};
303 	
304 	jsonq.name = Query.fullformatstring(jsonq);
305 	
306 	return jsonq;//JSON.stringify(jsonq);
307 };
308 
309 Query.prototype.getcollectiontext = function(what) {
310 	var collection_text = "";
311 	for (var i = 0; i < this.collection.length; i++) {
312 		if (what == "index") {
313 			collection_text = collection_text + "," + this.collection[i].index;
314 		} else {
315 			collection_text = collection_text + "," + this.collection[i].name;	
316 		}
317 	}
318 	if (collection_text.length > 1) {
319 		collection_text = collection_text.substring(1);	
320 	}
321 	return collection_text;
322 };
323 Query.prototype.getcollectionindextext = function() {
324 	var collection_text = "";
325 	for (var i = 0; i < this.collection.length; i++) {
326 		collection_text = collection_text + "," + this.collection[i].index;
327 	}
328 	if (collection_text.length > 1) {
329 		collection_text = collection_text.substring(1);	
330 	}
331 	return collection_text;
332 };
333 
334 Query.collectiontext = function(json) {
335 	var collection_text = "";
336 	if (json.collections != "null"){
337 		$.each(json.collections,function(i,item){
338 			collection_text = collection_text + "," + item.name;
339 		});
340 		if (collection_text.length > 1) {
341 			collection_text = collection_text.substring(1);	
342 		}
343 	}
344 	return collection_text;
345 };
346 
347 Query.columnstext = function(json) {
348 	var columns_text = "";
349 	if (json.columns != "null"){
350 		$.each(json.columns,function(i,item){
351 			columns_text = columns_text + "," + item;
352 		});
353 		if (columns_text.length > 1) {
354 			columns_text = columns_text.substring(1);	
355 		}
356 	}
357 	return columns_text;
358 };
359 
360 Query.optionstext = function(json) {
361 	var options_text = "";
362 	if (json.options == undefined){
363 		return "";
364 	}
365 	if (json.options != "null"){
366 		$.each(json.options,function(i,item){
367 			options_text = options_text + "," + item;
368 		});
369 		if (options_text.length > 1) {
370 			options_text = options_text.substring(1);	
371 		}
372 	}
373 	return options_text;
374 };
375 
376 Query.fullformatstring = function (json) {
377 	var qs = json.querystring;
378 	var sqs = json.squerystring;
379 	
380 	if (qs == "[NULL]") {
381 		qs = null;
382 	}
383 	if (sqs == "[NULL]") {
384 		sqs = null;
385 	}
386 	var collection_text = Query.collectiontext(json);
387 	
388 	var full_str = "";
389 	var len = formatquerystring_len;
390 	
391 	if (sqs != null) {
392 		if (sqs.length > len){
393 			full_str = sqs.substring(0,len) + "..| ";
394 		} else {
395 			sqs = sqs + "                                     ";
396 			full_str = sqs.substring(0,len) + "  | ";
397 		}
398 	}
399 	if (qs != null) {
400 		qs = Query.simplequerystring(qs);
401 		if (qs.length > len){
402 			full_str = full_str + qs.substring(0,len) + "..| ";
403 		} else {
404 			qs = qs + "                                     ";
405 			full_str = full_str + qs.substring(0,len) + "  | ";
406 		}
407 	}
408 	if (collection_text.length > (len - 6)) {
409 		full_str = full_str + collection_text.substring(0,len);
410 	} else {
411 		full_str = full_str + collection_text;
412 	}
413 	
414 	return full_str;
415 };
416 
417 Query.queryliststring = function(squery, query) {
418 	var s_squery = "";
419 	var s_query = "";
420 	var str = "";
421 	
422 	if (squery != null){
423 		s_squery = squery;
424 	}
425 	if (query != null){
426 		s_query = query;
427 	}
428 	if (s_squery.length != 0 && s_query.length != 0){
429 		str = squery + " & (" + Query.simplequerystring(query) +  ")";
430 	} else if (s_squery.length != 0) {
431 		str = squery;
432 	} else {
433 		str =  Query.simplequerystring(query);
434 	}
435 	return str;
436 };
437 
438 Query.simplequerystring = function (querystring) {
439 
440 	if (querystring == null){
441 		return "";
442 	}
443 	querystring = Url.decode(querystring);
444 	
445 	var arr_and = querystring.split(" and ");
446 	var simple_form = "";
447 	var simple_form_all = "";
448 	var rel = "";
449 	
450 	for( var i=0;i<arr_and.length;i++){
451 		arr_and[i] = $.trim(arr_and[i]);
452 		var arr_or = arr_and[i].split(" or ");
453 		simple_form = "";
454 		for( var j=0;j<arr_or.length;j++){
455 			arr_or[j] = $.trim(arr_or[j]);
456 			while (arr_or[j].substring(0,1) == "(" ) {
457 				arr_or[j] = arr_or[j].substring(1,arr_or[j].length);
458 				arr_or[j] = $.trim(arr_or[j]);
459 			}
460 			while ( arr_or[j].substring(arr_or[j].length-1) == ")"){
461 				arr_or[j] = arr_or[j].substring(0,arr_or[j].length-1);
462 				arr_or[j] = $.trim(arr_or[j]);
463 			}
464 			if (j > 0) { 
465 				rel = " or ";
466 			} else {
467 				rel = "";
468 			}
469 			simple_form = simple_form + rel + arr_or[j];
470 		}
471 		if (arr_or.length > 1){
472 			simple_form = "(" + simple_form + ") ";
473 		}
474 		if (i > 0) { 
475 			rel = " and  ";
476 		} else {
477 			rel = "";
478 		}
479 		simple_form_all = simple_form_all + rel + simple_form;
480 		
481 	}
482 	
483 	
484 	//notifyUser("querystring:" + querystring, 'debug');
485 	//notifyUser("simplequerystring:" + simple_form_all, 'debug');
486 	return simple_form_all;
487 };
488 
489 Query.prototype.render = function () {
490 /*
491 	var x = "<div id='" + this.listid + "' class='query_wrapper ui-widget' ><div class='query_header ui-widget-header ui-state-default ui-corner-top'>" +
492 	"<span class='cmd cmd_get'></span><span class='cmd cmd_save'></span><span class='cmd cmd_del'> </span>" +
493 	"<span class='query_id'>" + 	this.listid + "</span>: <span class='query'>" +
494 	this.getcollectiontext("name") + ":" + Query.queryliststring(this.squery, this.query) + ", repository:" + this.repository.toString() + "</span>" + 
495 			"<a class='cmd cmd_xml' target='_blank' href='" + this.link("xml") + "'>xml</a> <a class='cmd cmd_link' target='_blank' href='" + this.link("fullpage") + "' >link</a></div>" +
496 		//	<span class='cmd cmd-xml'></span><span class='cmd cmd-page'></span><span class='cmd cmd-link'></span></div>" +		
497 			//"<div class='ui-context-dialog columns-wrapper'><div class='query-columns'></div><span class='cmd cmd_del'></span></div><div class='result ui-widget-content ui-corner-bottom'></div>";
498 			"<div class='result ui-widget-content ui-corner-bottom'></div>";
499 			*/
500 	/*
501 	var x = $('#querylistelement').html().toString();
502 	x.replace('querylistelement', this.listid);
503 	$(x).find(".query-id").text(this.listid);
504 	$(x).children().children(".query").text(this.getcollectiontext("name") + ":" + Query.queryliststring(this.squery, this.query) + ", repository:" + this.repository.toString());
505 	*/
506 	// FIXME: this is not nice, there should be a function providing the formatted string of the query.
507 	//var coll = (this.getcollectiontext("name") != "" ) ? " in " + this.getcollectiontext("name") : "";  
508 	var x = "<div id='" + this.listid + "' class='query_wrapper ui-widget' name='query' ><div class='query_header ui-widget-header ui-state-default ui-corner-top'>" +
509 	"<span class='cmd cmd_get'></span><span class='cmd cmd_del'> </span>" +
510 	"<span class='query_id'>" + this.listid + "</span>: <span class='query'>" +
511 	this.toString() + 
512 	//Query.queryliststring(this.squery, this.query) + coll + " @" + this.repository.toString() + 
513 	"</span>" + 
514 			"</div>" +
515 			"<div class='result ui-widget-content ui-corner-bottom'></div>";
516 	addToQuerylist(x);	
517 	
518 	this.container = $('#' + this.listid );
519 
520 	notifyUser("DEBUG: setting up removing query:" + $(this).closest('.query_wrapper').attr('id'));
521 	$(this.container).children('.query_header').find('.cmd_del').click(function(event) {
522 		notifyUser("DEBUG: removing query:" + $(this).closest('.query_wrapper').attr('id'));
523 		queryset.removequery($(this).closest('.query_wrapper').attr('id'));
524 	});
525 	
526 	createTooltip(this.container);
527  };
528  
529  Query.prototype.open = function (type) {
530 	 if (type != null)
531 	    window.open(this.link(type));
532 	 else
533 		window.open(this.link());
534 };
535  
536  Query.prototype.link = function (type) {
537 	 var uri="";
538 	 if (type=="fullpage")  {
539 		 uri = link('base',this.query_uri());
540 	 } else {
541 		 if (type == "xml"){
542 			 uri = link('sru',this.sruquery_uri());
543 		 } else {
544 			 uri = link('recordset',type, this.query_uri());
545 		 }		
546 	 }
547 	return uri;
548  };
549   
550  Query.prototype.link_obsoleted = function () {
551 	 
552 		// JSON conversion
553 	 /*
554 		if (this.query.length == 0){
555 			xqstring = "[NULL]";
556 		} else {
557 			xqstring = this.query;
558 		}
559 		if (this.squery.length == 0){
560 			xsquery = "[NULL]";
561 		} else {
562 			xsquery = this.squery;
563 		}
564 	 */
565 	 	var jsonq = {"squerystring":this.squery, "querystring":this.query, "searchclauses":"null" , "collections" : this.json_coll, "columns" : this.json_cols};
566 
567 		var uri = "?query=" + JSON.stringify(jsonq) + "&startItem=" + this.startItem + "&maximumItems=" + this.maximumItems;
568 		return uri;
569 };
570  Query.prototype.submit = function () {
571 		var uri = link('recordset',this.format, this.query_uri());
572 		var query = this;
573 		
574 		notifyUser("submitting query:" +  uri);
575 		this.container.find('.result').load( uri, function() {
576 					notifyUser("result-loaded",'debug');
577 					
578 					var get = $(this).parent().find('.cmd_get');				
579 
580 					get.removeClass('cmd_get');
581 					get.addClass('cmd_up');
582 					// get.show();
583 					
584 					var result_header = $(this).children('.result-header');
585 					
586 					var q_header;
587 					q_header = $(this).parent().find('.query_header');					
588 					q_header.append(result_header);
589 					
590 				 	addDetailFunctionality(q_header, query);
591 				 	
592 					createTooltip($(this));
593 				});
594 
595 	};
596 	
597 Query.prototype.resubmit = function () {
598 	
599 	var uri = link('recordset',this.format, this.query_uri());
600 	var qid = this.listid;
601 	var q_uri = this.query_uri();
602 	var query = this;
603 	
604 	notifyUser("resubmitting query:" +  uri);
605 	
606 	var get = $('#' + qid ).find('.cmd_up');
607 	if (get.length == 0) {
608 		get = $('#' + qid ).find('.cmd_down');
609 	}
610 	get.addClass('cmd_get');
611 	get.removeClass('cmd_up');
612 	get.removeClass('cmd_down');
613 	// get.show();	
614 
615 	$('#' + qid ).children('.result').children().remove();
616 	$('#' + qid ).find('.result').load( uri, function() {
617 				// update link-hrefs
618 				var qid = $(this).closest('.query_wrapper').attr("id");
619 				notifyUser("result-loaded ID:" + qid,'debug');
620 				
621 				var q = queryset.getQuery(qid);
622 				$('#' + qid ).find(".cmd_link").attr("href", q.link("fullpage"));
623 				
624 				var get = $(this).parent().find('.cmd_get');				
625 				get.removeClass('cmd_get');
626 				get.addClass('cmd_up');
627 				// get.show();	
628 				
629 				var result_header = $(this).children('.result-header');
630 				
631 				var q_header;
632 				q_header = $(this).parent().find('.query_header');
633 				q_header.children('.result-header').remove();
634 				
635 				q_header.append(result_header);				
636 			 	addDetailFunctionality(q_header, query);
637 			});
638 
639 };
640 
641 Query.prototype.updateColumns = function(selectionlist){
642 	if (selectionlist != undefined){
643 		if (selectionlist.autoSelected()){
644 			this.columns = "";
645 		} else
646 		{
647 			this.columns = selectionlist.listwidget.getListText();
648 		}
649 	}
650 };
651 
652 Query.prototype.next = function(pages){
653 	var start = 0;
654 	var num = 0;
655 	var max_value = $('#' + this.listid ).find('.result-header').attr("max_value");
656 	
657 	if (parseInt(this.startItem) + pages * page_record_count >= 1){
658 		start =	parseInt(this.startItem) + pages * page_record_count ;
659 	} else if (parseInt(this.startItem) + pages * page_record_count + page_record_count - 1 >= 1){
660 		start =	1 ;
661 	}
662 	if (start > 0){
663 		if (start + page_record_count - 1 <= max_value) {
664 			num = page_record_count;
665 		} else if (start <= max_value){
666 			num = max_value - start;
667 		}
668 	
669 		if (num > 0){
670 			this.startItem = start;
671 			this.maximumItems = num;
672 			this.resubmit();
673 			updateQueryDetailPane(this);
674 		}
675 	}
676 };
677 
678 var queryset_container = $("#querylist"); 
679 
680 /**
681  * A singleton-object holding all queries.
682  * @constructor
683 */ 
684 var queryset = { queries: [],
685 	container: '#querylist',
686 	recordrowselected: undefined,
687 	
688 	addquery: function (query){
689 			
690 		this.queries[this.queries.length] = query;
691 		query.listid = "q" + this.queries.length;
692 		query.render();				
693 		query.submit();		
694 	},
695 
696 	removequery: function (qid) {
697 		notifyUser("removing query:"  + qid);
698 		
699 		 for (var i = 0; i < this.queries.length; i++) {
700 			if (this.queries[i].listid == qid) {
701 				this.queries.splice(i, 1);
702 			} 
703 		}	
704 		$('#' + qid).remove();
705 		notifyUser("query removed, new queries.length:"  + this.queries.length);
706 		
707 	},
708 
709 	getsquery: function(qid) {
710 		var qstring = "";
711 		
712 		for (var i = 0; i < this.queries.length; i++) {
713 			if (this.queries[i].listid == qid) {
714 				qstring = this.queries[i].squery;
715 			} 
716 		}
717 		if (qstring == null){
718 			qstring = "";
719 		}
720 		return qstring;
721 	},
722 	getquerystring: function(qid) {
723 		var qstring = "";
724 		
725 		for (var i = 0; i < this.queries.length; i++) {
726 			if (this.queries[i].listid == qid) {
727 				qstring = this.queries[i].query;
728 			} 
729 		}
730 		if (qstring == null){
731 			qstring = "";
732 		}
733 
734 		return qstring;
735 	},
736 	getcollections: function(qid) {
737 		var coll = "";
738 		var json_coll, json_temp;
739 		
740 		for (var i = 0; i < this.queries.length; i++) {
741 			if (this.queries[i].listid == qid) {
742 				coll = this.queries[i].collection;
743 			} 
744 		}		
745 		if (coll.length == 0) {
746 			json_coll = {};
747 			json_coll = "null";
748 		} else { 
749 			json_coll = [{}];
750 			for (var i = 0; i < coll.length; i++) {
751 				json_coll[i] = {"index" : coll[i].index, "name" :coll[i].name};
752 			}
753 		}
754 		return json_coll;
755 	},
756 	
757 	getcolumns: function(qid) {
758 		var cols = "";
759 		var json_cols, json_temp;
760 		
761 		for (var i = 0; i < this.queries.length; i++) {
762 			if (this.queries[i].listid == qid) {
763 				cols = this.queries[i].columns;
764 			} 
765 		}
766 		
767 		if (cols == "") {
768 			json_cols = {};
769 			json_cols = "null";
770 		} else {  
771 			var pos = cols.indexOf(",", 0);
772 			var i = 0;
773 			
774 			json_cols = [{}];
775 			while (pos > -1){
776 				if (pos > -1){
777 					json_cols[i] = cols.substring(0,pos);
778 				} else {
779 					json_cols[i] = cols;
780 				}
781 				cols = cols.substring(pos+1);
782 				pos = cols.indexOf(",", 0);
783 				i = i+1;
784 			}
785 			
786 			json_cols[i] = cols;
787 
788 			
789 		}
790 		return json_cols;
791 	},
792 	getoptions: function(qid) {
793 		var opts = null;
794 		var json_opts;
795 		
796 		for (var i = 0; i < this.queries.length; i++) {
797 			if (this.queries[i].listid == qid) {
798 				opts = this.queries[i].options;
799 			} 
800 		}
801 
802 		if (opts != null) {
803 			json_opts = [{}];
804 			json_opts[0] = opts;
805 		}
806 		return json_opts;
807 	},
808 	resubmit: function(qid){
809 		var query = queryset.queries[qid.substring(1)-1];
810 		
811 		query.repository = getSelectedRepository();
812 		query.startItem = $('#' + qid ).find('.start_record').val();
813 		query.maximumItems = $('#' + qid ).find('.maximum_records').val();
814 		query.resubmit();
815 
816 	},
817 	
818 	getQuery: function(qid){
819 		var query = queryset.queries[qid.substring(1)-1];
820 		return query;
821 	},
822 	/*
823 	next: function(qid,pages){
824 		var query = queryset.queries[qid.substring(1)-1];
825 		var start = 0;
826 		var num = 0;
827 		var max_value = $('#' + qid ).find('.result-header').attr("max_value");
828 		
829 		if (parseInt(query.startItem) + pages * page_record_count >= 1){
830 			start =	parseInt(query.startItem) + pages * page_record_count ;
831 		} else if (parseInt(query.startItem) + pages * page_record_count + page_record_count - 1 >= 1){
832 			start =	1 ;
833 		}
834 		if (start > 0){
835 			if (start + page_record_count - 1 <= max_value) {
836 				num = page_record_count;
837 			} else if (start <= max_value){
838 				num = max_value - start;
839 			}
840 		
841 			if (num > 0){
842 				query.startItem =	start;
843 				query.maximumItems = num;
844 				query.resubmit();
845 			}
846 		}
847 		
848 	},
849 	*/
850 	recorddetailselection: function(recordrow){
851 		if (this.recordrowselected != undefined){
852 			$(this.recordrowselected).removeClass('detailselection');
853 		}
854 		this.recordrowselected = recordrow;
855 		$(this.recordrowselected).addClass('detailselection');
856 	}
857 	
858 	
859 };
860 
861 $('#querylist .cmd_columns').live('click',function(){
862 	notifyUser("DEBUG: #querylist.cmd_columns");
863 	$(this).closest('.query_wrapper').find('.columns-wrapper').toggle();
864 });
865 
866 function query_wrapper_add_column(elem){
867 	var slid = $(elem).closest('.query-columns').find('.widget-wrapper').attr('id');
868 	var sl = selectionlistset.getselectionlist(slid);
869 	if (sl.autoSelected()){
870 		sl.select(0);
871 	}
872 	sl.listwidget.add(new ListItem($(elem).closest('.treecol').children('.column-elem').text()));
873 	
874 	//$(elem).data('query').updateColumns(slid);
875 
876 };
877 
878 function addDetailFunctionality(q_header, query){
879 	
880 	$(q_header).data('query',query);
881 	q_header.find('.cmd_reload').data('query',query);
882 	q_header.find('.cmds .cmd_save').data('query',query);
883  	q_header.find('.cmd_reload').click(function() {
884  		/*
885  		var qid;
886  		if ($(this).parent().attr('class') == 'result-header'){
887  			qid = $(this).closest('.query_wrapper').attr("id");
888  		} else {
889  			var did = $(this).closest('.detail-wrapper').attr("id");
890  			var slid = $(this).closest('.detail-wrapper').find('.selectionlist-widget').attr("id");
891  			var detail = detailcaller.getdetail(did);
892  			qid = detail.temp_id;
893  			
894  			var q = queryset.getQuery(qid);
895  			if (selectionlistset.getselectionlist(slid).autoSelected()){
896  	 			q.columns = "";
897  			} else
898  			{
899  	 			q.columns = selectionlistset.getselectionlist(slid).listwidget.getListText();
900  			}
901   		}
902 		//queryset.resubmit(qid);
903 		*/
904  		// update columns if  reloaded from detail pane
905  		/*
906  		if ($(this).parent().attr('class') != 'result-header'){
907  			var slid = $(this).closest('.detail-wrapper').find('.selectionlist-widget').attr("id");
908  			if (selectionlistset.getselectionlist(slid).autoSelected()){
909  				$(this).data('query').columns = "";
910  			} else
911  			{
912  				$(this).data('query').columns = selectionlistset.getselectionlist(slid).listwidget.getListText();
913  			}
914  		}
915  		*/
916  		/*
917  		var slid = $(this).closest('.detail-wrapper').find('.selectionlist-widget').attr("id");
918  		if (slid != undefined){
919  	 		$(this).data('query').updateColumns($(this).data('detail'));
920  		}
921  		*/
922  		$(this).data('query').updateColumns($(this).data('selectionlist'));
923  		$(this).data('query').resubmit();
924 	});
925 	q_header.find('.cmd_prev').click(function() {
926 		/*
927 		var qid = $(this).closest('.query_wrapper').attr("id");
928 		queryset.next(qid,-1);
929 		*/
930 		$(this).closest('.query_header').data('query').next(-1);
931 	});
932 	q_header.find('.cmd_next').click(function() {
933 /*
934 		var qid = $(this).closest('.query_wrapper').attr("id");
935 		queryset.next(qid,1);
936 		*/
937 		$(this).closest('.query_header').data('query').next(1);
938 	});
939 	
940 	q_header.find('.value-format').data('query',query);
941 	q_header.find('.value-format').change(function(){
942 		/*
943 		var did = $(this).closest('.detail-wrapper').attr("id");
944  		var qid = detailcaller.getdetail(did).temp_id;
945 		var q = queryset.getQuery(qid);		
946 		queryset.resubmit(qid);
947 		*/
948 		$(this).data('query').format = $(this).find('option:selected').val();
949 		$(this).data('query').resubmit();
950 	});
951 	//q_header.find('.cmd_add').click(function(){
952 	//q_header.find('.cmd_columns').data('query', query);
953 	q_header.find('.cmd_columns').click(function(){
954 		query_wrapper_add_column($(this));
955 		//$(this).data('query').resubmit();
956 	});
957 	q_header.find('.columns-wrapper').hide();
958 	q_header.find('.terms-tree').treeTable({initialState:"collapsed"});
959 
960 
961 };
962