var SQL_ISSUED_TO_BORROWER = "select barcode_ ,title_,category_,DATE_FORMAT(issue_,'%d/%m/%Y') as issue_,DATE_FORMAT(return_,'%d/%m/%Y') as return_,fine_,copies.renew_,reserved_ from catalogue,copies  where catalogue.id_ = copies.catalogue_ and borrower_ = '$borrower' and status_ = 'LOA' order by return_";
var SQL_ISSUED_TO_BORROWER_COLS = "barcode_,title_,category_,issue_,return_,fine_,renew_,reserved_,ret_,ren_";
var SQL_BORROWER_ADDRESS = "select members.id_ as id_,members.barcode_ as barcode_,category_,forename_,surname_,dob_,email_,adr1_,trap_ from members,address where members.barcode_ = '$borrower' and members.barcode_ = address.barcode_ and address.active_ = 'y'";
var SQL_BORROWER_ADDRESS_COLS = "id_,barcode_,category_,forename_,surname_,dob_,email_,adr1_,trap_";
var SQL_BORROWER_SURNAME = "select members.id_ as id_,members.barcode_ as barcode_,CONCAT_WS(' ',surname_,forename_,adr1_) as sindex_,category_ from members,address where members.barcode_ = address.barcode_ and surname_ like '$borrower' order by sindex_";
var SQL_BORROWER_SURNAME_COLS = "id_,barcode_,forename_,surname_,adr1_,dob_,email_,trap_";
var SQL_BORROWER_CATEGORY_LIST = "select description_ from borrower_category"; 

var SQL_CATALOGUE = "select catalogue.barcode_ as barcode_,title_,author_,category_,status_,trap_,borrower_ from catalogue,authors where catalogue.barcode_ = '$barcode' and authors.barcode_ = catalogue.barcode_;"
var SQL_CATALOGUE_BARCODE = "select id_ from catalogue where catalogue.barcode_ = '$barcode';"
var SQL_CATALOGUE_AUTHOR = "select id_ from authors where authors.barcode_ = $barcode;"
var SQL_CATALOGUE_COLS = "title_,author_,category_,status_,trap_";
var SQL_CATALOGUE_TITLE = "select left(rpad(title_,60,' '),50) as title_,lpad(barcode_,9,'.') as barcode_ from catalogue where title_ like '$title' order by title_";
var SQL_CATALOGUE_TITLE_WITH_AUTHOR = "select catalogue.barcode_ as barcode_,title_,author_,category_,status_,trap_ from catalogue,authors where title_ like '$title' and authors.barcode_ = catalogue.barcode_";
var SQL_LOANS = "select borrower_,status_ from catalogue where barcode_ = '$barcode'";

var SQL_ITEM_CATEGORY_LIST = "select description_ from item_category"; 

var SQL_CATEGORY_MATRIX = "select period_,return_ from lending_categories where lower(borrower_) = lower('$borrower') and lower(item_) = lower('$item')"; 
var SQL_SPECIAL_DATE = "select return_ from `specialdates` where '$myreturn' >= holidaystart_ and '$myreturn'  <= holidayend_ and active_ = 'y'"
var SQL_BORROWER_CATEGORY_RETURN = "select period_,return_ from borrower_category where category_ = '$category'"; 
var SQL_ITEM_CATEGORY_RETURN = "select period_,return_ from item_category where category_ = '$category'"; 


var global_valid_borrower = false;
var global_valid_item = false;
var global_borrower_category = '';
var global_borrower_surname = '';
var global_borrower_forename = '';
var global_item_category = '';
var global_item_loan = 0;
var global_item_renew = 0;
var global_item_borrower = '';
var global_item_title = '';
var global_today = '';
var global_renew_date = '';
var global_item_return = '';
var global_item_catalogue = '';
var global_item_reserved = ''; 
var mygrid;
Number.prototype.mod = function(n) {
return ((this%n)+n)%n;
}

Date.prototype.addBusDays = function(dd) {
	var wks = Math.floor(dd/5);
	var dys = dd.mod(5);
	var dy = this.getDay();
	if (dy === 6 && dys > -1) {
   		if (dys === 0) {
   			dys-=2; dy+=2;
   		}
   		dys++; dy -= 6;
   	}
	if (dy === 0 && dys < 1) {
   		if (dys === 0) {
   			dys+=2; dy-=2;
   		}
   		dys--; dy += 6;
   	}
	if (dy + dys > 5) 
		dys += 2;
	if (dy + dys < 1) 
		dys -= 2;
	this.setDate(this.getDate()+wks*7+dys);
}

function m120(){
	menu.hide();
	GridDiv("");
	GridStyle('800px','260px');
	loadIssueTab("#workbar","m120.div");
	IssueSetMouseKeys();
	$('#borrower_box').bind('keypress', function(e) { 
        if(e.keyCode==13){
        	if($("#borrower_box").val() == ''){
        		GoToField("#item_box"); 
        	}
        	else{
        		global_desk_state = '';
        		mygrid.clearAll();
        		GoLocate();
        	}
        } 
	});
	$('#borrower_box').bind('click', function(e) { 
		global_desk_state = '';
		mygrid.clearAll();
	});
	$('#item_box').bind('keypress', function(e) { 
        if(e.keyCode==13){
        	if($("#item_box").val() == ''){
        		GoReset();
        		GoToField("#borrower_box");
        	}
        	else
        		GoLocate();
        } 
	});
	GoIssueDesk();
}

function m121(){
	menu.hide();
	GridDiv("");
	GridStyle('800px','260px');
	loadTab("#workbar","m121.div");
	IssueSetMouseKeys();
	$('#item_box').bind('keypress', function(e) { 
        if(e.keyCode==13){
        	GoQuickItem();
        	e.preventDefault();
        	return(false);
        }
	});
	GoQuickDesk();
}

function GoQuickDesk(){
	mygrid = new dhtmlXGridObject('gridholder');
	mygrid.setHeader("Barcode,Author,Title,Borrower"); 
	mygrid.setColTypes("ro,ro,ro,ro");
	mygrid.setInitWidths("80,100,480,80"); 
	mygrid.setColAlign("left,left,left,left");  
	mygrid.setImagePath("imgs/");
	mygrid.setSkin("light"); 
	mygrid.init();
	mygrid.enableColumnAutoSize(true);
	GoToField("#item_box");
}

function GoQuickItem(){
	$("#trap_").text('');
	var item = $("#item_box").val();
	var result = new Array();
	var SQL = $("#copyfrom1").val(); 
	var SQLCOLS = $("#copycols1").val(); 
	SQL = SQL.replace('$item',item);
   	AjaxSql("item_box",SQL,SQLCOLS,result);		//results in result[i] etc
 	if(result[0] != '0'){		//number is valid
  		var x = result[1].split('\t');
   		$("#title_").val(x[0] + " " + x[1] + " " +  x[2] + " " + result[5]);
		if(result[3] != '' || result[4] != ''){
			$("#trap").css("background-color", "red"); 
			$("#trap_").text(result[3] + "  " + result[4]);
		}
	 	var count=mygrid.getRowsNum();
		var fill = new Array();
		fill[0] = item;
		fill[1] = x[1];
		fill[2] = x[0];
		if(result[6] == 'LOA')
			fill[3] = result[2];
		else
			fill[3] = '';
		mygrid.addRow(count+1,fill);
	}
	var SQL = "update copies set status_='SHE',renew_=0,overdue_=0 where barcode_ = '" + item + "'" 
	var result = UpdateRecord(SQL,"item_box");
	if(isNaN(result)){
		alert(result);
		return(false);
	}
	$("#item_box").val('');
//	$("#trap_").text('');
	GoToField("#item_box");
}

function GoIssueDesk(){
	var SQL = "select barcode_ ,title_,category_,DATE_FORMAT(issue_,'%d/%m/%Y') as issue_,DATE_FORMAT(return_,'%d/%m/%Y') as return_,fine_,copies.renew_,reserved_ from catalogue,copies  where catalogue.id_ = copies.catalogue_  and status_ = 'LOA' and return_ >= now() - INTERVAL 1 WEEK and return_ < now() order by return_ desc";
	var SQLCOLS = "barcode_,title_,category_,issue_,return_,fine_,renew_,reserved_,ret_,ren_";
	mygrid = new dhtmlXGridObject('gridholder');
	mygrid.attachEvent("onXLE", function() {
		
		showLoading(false);
	});
    mygrid.attachEvent("onXLS", function() {
        showLoading(true);
    });
	mygrid.setHeader("Barcode,Title,Category,Issued,Due,Fine,Renewed,Res,Ret,Ren"); 
	mygrid.setColTypes("ro,ro,ro,ro,ed,ro,ro,ch,ch,ch");
	mygrid.setInitWidths("70,240,80,65,80,60,80,40,40,40"); 
	mygrid.setColAlign("left,left,left,left,left,left,left,center,center,center");  
	mygrid.setColSorting("connector,connector,connector,connector,connector,connector,connector,na,na,na");
	mygrid.setImagePath("imgs/");
	mygrid.setSkin("light"); 
	mygrid.init();
	mygrid.enableColumnAutoSize(true);
	mygrid.attachEvent("onCheckbox",function(rId,cInd,state) {GoCheckBox(rId,cInd,state);});
	mygrid.attachEvent("onCellChanged", function(rId,cInd,nValue){
		if(cInd == 4){
			global_renew_date = nValue;
		}
 	});
	mygrid.attachHeader(",,,,,,,,<input type='checkbox' id='returnall' align='left' onClick='ReturnAll(this.value);' title='Return all'/>,<input type='checkbox' id='renewall' align='left' onClick='RenewAll(this.value);'/>");
//	mygrid.loadXML("connector.php?cmd="+SQL+"&cols="+SQLCOLS+"&");
	GoToField("#borrower_box");
}

function GoLocate(){
	$("#trap_").text('');
	var SQL = "select DATE_FORMAT(now(),'%d/%m/%Y') as thedate_";
	var global_today = GetServerDate(SQL);
	var _borrower = $("#borrower_box").val();
	var _item = $("#item_box").val();
	mygrid.attachEvent("onXLE",	function(){ DisableReserveColumn();});
	
//alert("v " + v + " w " + w + " valid borrower " + global_valid_borrower + " valid item " + global_valid_item);	
   	if(_borrower != '' && _item == '')			//a borrower and no item
   		BorrowerLoans(_borrower);				//display borrower and loan details
	else if(_item != '' && _borrower == ''){ 	//an item and no borrower

		_status = GetStatus(_item);				//get item _status
		if(_status == 'SHE'){
			GoToField("#borrower_box");
		}
		else if(_status == 'LOA'){					//if item is onloan
			_borrower = GetBorrower(_item);		//get borrower 
			if(_borrower == ''){
				alert('Item is unavailable');
				return;
			}
			$("#borrower_box").val(_borrower);
			BorrowerLoans(_borrower);		//display borrower and loan details
			//wait for next click
			GoToField("#item_box");
		}
		else if(_status == 'NEW')
			$("#trap").text('');
		else
			alert('Item is unavailable');
	}
	else if(_borrower != '' && _item != ''){ 	//borrower and item
		if(OnLoan(_borrower,_item))				//if item on loan to this borrower
			DoReturn(_item);							//return the item
		else {
			_status = GetStatus(_item);			//get item _status
			if(_status == 'SHE')					//if on the shelf
				DoIssue(_borrower,_item);		//issue to this borrower
			else if(_status == 'LOA')			//if on loan to another borrower
				DoReserve(_borrower,_item);						//reserve
			else
				alert('Item is unavailable');
		}
	}
	
}

//display borrower and loans
function BorrowerLoans(){
	var result = new Array();
	var v = $("#borrower_box").val();
	var SQL = $("#copyfrom").val(); 
	var SQLCOLS = $("#copycols").val(); 
	SQL = SQL.replace('$borrower',v);
   	AjaxSql("borrower_box",SQL,SQLCOLS,result);		//results in result[i] etc
 	if(result[0] != '0'){		//number is valid
  		var x = result[1].split('\t');
   		global_borrower_category = result[3];
   		global_borrower_surname = x[0];
   		global_borrower_forename = x[1];
		$("#sindex_").val(x[1] + " " + x[0] + " " +  x[2] + " " +  x[4] + " " + result[3]);
		$("#trap_").text(result[2]);
		var v = $("#borrower_box").val();
 //get the loans
		var SQL = SQL_ISSUED_TO_BORROWER; 
		SQL = SQL.replace('$borrower',v);
//		prompt("",SQL);
		mygrid.loadXML("connector.php?cmd="+SQL+"&cols=" + SQL_ISSUED_TO_BORROWER_COLS + "&");
		GoToField("#item_box");
  	}
  	else{	//now check surnames
  		DeskMsg("Unknown Borrower");
 		QuickBorrowerAdd('Quickly add a new borrower');
	}
 	ReserveCounter(v);
 //	var count=mygrid.getRowsNum();
 //	alert("count " + count);
 //	var ids=mygrid.getAllRowIds();
 //	alert("ids " + ids);
 	
}

function EditRenew(rId,nValue){
	var item = mygrid.cells(rId,0).getValue();
	GetStatus(item);
	DoRenew($("#borrower_box").val(),item,nValue,rId);
	mygrid.cells(rId,8).setValue(0);
	mygrid.cells(rId,9).setValue(1);
	mygrid.cells(rId,4).setValue(nValue);
	mygrid.setRowTextStyle(rId, "color: blue; ");
}

function GetStatus(item){			//see if item is on the shelf
	var result = new Array();
	var SQL = $("#copyfrom1").val(); 
	var SQLCOLS = $("#copycols1").val(); 
	SQL = SQL.replace('$item',item);
   	AjaxSql("item_box",SQL,SQLCOLS,result);		//results in result[i] etc
 	if(result[0] != '0'){		//number is valid
  		var x = result[1].split('\t');
   		global_item_category = result[5];
   		global_item_title = x[0];
   		global_item_catalogue = x[2];
   		global_item_loan = result[7];
   		global_item_renew = result[8];
   		global_item_return = result[9];
   		global_item_borrower = result[2];
   		global_item_reserved = result[10];
   		var _status = result[6];
		$("#title_").val(x[0] + " " + x[1] + " " +  x[2] + " " + result[5]);
		if(result[3] != '' || result[4] != '')
			$("#trap_").text(result[3] + " : " + result[4]);
		return(_status);
 	}
  	else{
  		DeskMsg("Unknown Item");
 		QuickItemAdd('Quickly add a new item');
	}
 	return('NEW');
}



function OnLoan(_borrower,_item){		//see if this item is on loan to this borrower
	var result = new Array();
	var SQL = "select status_,reserved_ from copies where borrower_ = '" + _borrower + "'" + " and barcode_ = '" + _item + "'";
	var SQLCOLS = "status_,reserved_"; 
	AjaxSql("item_box",SQL,SQLCOLS,result);		//results in result[i] etc
 	if(result[0] != '0'){		//number is valid
 		var _status = result[1];
   		global_item_reserved = result[2];
 		if(_status == 'LOA')	//its on loan to this borrower
 			return(true);
 		else
 			return(false);
 	}
  	else
  		return(false);
}

function GetBorrower(item){				//get the borrower from the item
	var result = new Array();
	var SQL = $("#copyfrom1").val(); 
	var SQLCOLS = $("#copycols1").val(); 
	SQL = SQL.replace('$item',item);
   	AjaxSql("item_box",SQL,SQLCOLS,result);		//results in result[i] etc
   	var _borrower;
 	if(result[0] != '0'){		//number is valid
  		_borrower = result[2];
 	}
 	else
 		_borrower = '';
 	return(_borrower);
}


var ingrid = false;
function DoIssue(_borrower,_item){
	ingid = false;
	var rowCnt = 0;
	if(CheckIssuePriv('loans_',"loan") == false)
		return;
	var _return = CalcReturnDate();
	var _issue = SetDate(GetDate());
	var _loan = 0;
	_loan = parseInt(global_item_loan,10) + 1;
	var SQL = "update copies set " +
			"borrower_='" + _borrower + "'," +
			"status_='LOA'," +
			"issue_='" + _issue + "'," +
			"return_='" + SetDate(_return) + "'," +
			"overdue_=0," +
			"reserved_=" + "''," +
			"loan_=" + _loan + "," +
			"fine_=0 " +
			"where barcode_='" + _item + "'";
	var result = UpdateRecord(SQL,"item_box");

	if(isNaN(result)){
		alert(result);
		return(false)
	}
 	var count=mygrid.getRowsNum();
// 	alert("first count " + count);
 	var ids=mygrid.getAllRowIds();
// 	alert("ids " + ids);
 	var x = ids.split(',');
// 	alert("length " + x.length);
 	for(var i=0;i<x.length;i++){
//alert("gridfind "+ x[i] +" item " + _item)
		if(x[i] == '')
			break;
 		var cellObj = mygrid.cellById(x[i], 0);
 		var barcode = cellObj.getValue();
 		if(barcode == _item){ //we just do the update
// 		alert("found "+ x[i] +" item " + _item)
 			mygrid.setRowTextStyle(x[i], "color: blue; ");
 			mygrid.cells(x[i],8).setValue(0);
 			mygrid.cells(x[i],9).setValue(0);
 			ingrid = true;
 			break;
 		}
 	}
// 	alert("ingrid " + ingrid);
	if(ingrid == false){
		var fill = new Array();
		fill[0] = _item;
		fill[1] = global_item_title;
		fill[2] = global_item_category;
		fill[3] = GetDate();
		fill[4] = _return;
		fill[5] = "0.00";
		fill[6] = "";
		fill[7] = "";
		fill[8] = "";
		fill[9] = "";
		mygrid.addRow(count+1,fill);
	}
// 	var count=mygrid.getRowsNum();
// 	alert("last count " + count);
// 	var ids=mygrid.getAllRowIds();
// 	alert("ids " + ids);
	$("#item_box").val('');
	GoToField("#item_box");
	ReserveIssue(_borrower,_item);
	return(true);
}

//make sure this borrower has privileges
function CheckIssuePriv(type_,msg){
	var result = new Array();
//check loans max in matrix
	var matrixLoans = 999;
	var itemLoans = 999;
	var borrowerLoans = 999;
	var SQL= "select " + type_ + " from lending_categories " +
			"where lower(borrower_) = lower('" +
	global_borrower_category +
	"') and lower(item_) = lower('" +
	global_item_category + "')"; 
//prompt("matrix",SQL);
	var SQLCOLS = type_; 
	AjaxSql("item_box",SQL,SQLCOLS,result);		//results in result[i] etc
//alert(result);
	if(result[0] != '0'){		//number is valid
		matrixLoans = result[1];
	}
//alert("matrix loans " + matrixLoans);
//check loans max in borrower category
	var SQL= "select " + type_ + " from borrower_category " +
	"where lower(category_) = lower('" + global_borrower_category  + "')"; 
//prompt("borrower",SQL); 
	AjaxSql("item_box",SQL,SQLCOLS,result);		//results in result[i] etc
//alert(result);
	if(result[0] != '0'){		//number is valid
		borrowerLoans = result[1];
	}
//alert("borrower loans " + borrowerLoans);
//check loans max in item category
	var SQL= "select " + type_ + " from item_category " +
	"where lower(category_) = lower('" + global_item_category  + "')"; 
//prompt("item",SQL); 
	AjaxSql("item_box",SQL,SQLCOLS,result);		//results in result[i] etc
//alert(result);
	if(result[0] != '0'){		//number is valid
		itemLoans = result[1];
	}
//alert("item loans " + itemLoans);
//find current number of loans for this borrower
	var count=mygrid.getRowsNum();
//alert("current loans " + count);
	if(count >= borrowerLoans){
		alert("Maximum " + msg + " (" + borrowerLoans + ")" + " exceded for this borrower category");
		return(false);
	}
//find current number of loans for this item category
 	var ids=mygrid.getAllRowIds();
//alert("ids " + ids);
 	var x = ids.split(',');
//alert("length " + x.length);
 	count = 0;
 	for(var i=0;i<x.length;i++){
//alert("gridfind "+ x[i] +" item " + _item)
		if(x[i] == '')
			break;
 		var cellObj = mygrid.cellById(x[i], 2);
 		var category = cellObj.getValue();
 		if(category == global_item_category)
 			count++;
 	}
//alert("count " + global_item_category + " " + count);
	if(count >= itemLoans){
		alert("Maximum " + msg + " (" + itemLoans + ")" + " exceeded for this item category");
		return(false);
	}
	if(count >= matrixLoans){
		alert("Maximum " + msg + " (" + itemLoans + ")" + " exceeded for this borrower/item category");
		return(false);
	}
	return(true);
}

function CheckRenewPriv(type_,msg,rId){
	var result = new Array();
//check renews max in matrix
	var matrixRenews = 999;
	var itemRenews = 999;
	var borrowerRenews = 999;
	var SQL= "select " + type_ + " from lending_categories " +
			"where lower(borrower_) = lower('" +
	global_borrower_category +
	"') and lower(item_) = lower('" +
	global_item_category + "')"; 
//prompt("matrix",SQL);
	var SQLCOLS = type_; 
	AjaxSql("item_box",SQL,SQLCOLS,result);		//results in result[i] etc
//alert(result);
	if(result[0] != '0'){		//number is valid
		matrixRenews = result[1];
	}
//alert("matrix renews " + matrixRenews);

//check loans max in borrower category
	var SQL= "select " + type_ + " from borrower_category " +
	"where lower(category_) = lower('" + global_borrower_category  + "')"; 
//prompt("borrower",SQL); 
	AjaxSql("item_box",SQL,SQLCOLS,result);		//results in result[i] etc
//alert(result);
	if(result[0] != '0'){		//number is valid
		borrowerRenews = result[1];
	}
//alert("borrower renews " + borrowerRenews);
//check loans max in item category
	var SQL= "select " + type_ + " from item_category " +
	"where lower(category_) = lower('" + global_item_category  + "')"; 
//prompt("item",SQL); 
	AjaxSql("item_box",SQL,SQLCOLS,result);		//results in result[i] etc
//alert(result);
	if(result[0] != '0'){		//number is valid
		itemRenews = result[1];
	}
//alert("item renews " + itemRenews);
//find total current number of renews for this borrower
	var ids=mygrid.getAllRowIds();
//alert("ids " + ids);
 	var x = ids.split(',');
//alert("length " + x.length);
 	count = 0;
 	var totalRenew = 0;
 	for(var i=0;i<x.length;i++){
		if(x[i] == '')
			break;
 		var cellObj = mygrid.cellById(x[i], 6);
 		totalRenew  += parseInt(cellObj.getValue(),10);
 	}
//alert("current renews " + totalRenew);
	if(totalRenew >= borrowerRenews){
		alert("Maximum " + msg + " (" + borrowerRenews + ")" + " exceded for this borrower category");
		mygrid.cells(rId,9).setValue(0);
		return(false);
	}
//find total renews in this category
 	var totalRenew = 0;
 	for(var i=0;i<x.length;i++){
 //		alert(x[i]);
		if(x[i] == '')
			break;
		var cellObj = mygrid.cellById(x[i], 2);
		var category  = cellObj.getValue();
//alert("category " + category + " global_item_category " + global_item_category);
		if(category == global_item_category){
			var cellObj = mygrid.cellById(x[i], 6);
			totalRenew  += parseInt(cellObj.getValue(),10);
		}
 	}
//alert("itemrenews " + itemRenews);
//alert("category renews " + totalRenew);
	if(totalRenew >= itemRenews){
		alert("Maximum " + msg + " (" + itemRenews + ")" + " exceded for this item category");
		mygrid.cells(rId,9).setValue(0);
		return(false);
	}
	if(totalRenew >= itemRenews){
		alert("Maximum " + msg + " (" + itemRenews + ")" + " exceeded for this borrower/item category");
		mygrid.cells(rId,9).setValue(0);
		return(false);
	}
	return(true);
}

function DoReturn(item){
	mygrid.forEachRow(function(id){
		var cellObj = mygrid.cellById(id, 0);
		var barcode = cellObj.getValue();
		if(barcode == item){

			mygrid.selectRowById(id);
			mygrid.cells(id,8).setValue(1);
			mygrid.cells(id,9).setValue(0);
			var barcode = mygrid.cells(id,0).getValue();
			var SQL = "update copies set status_='SHE',renew_=0,overdue_=0 where barcode_ = '" + barcode + "'" 
			var result = UpdateRecord(SQL,"item_box");
			if(isNaN(result)){
				alert(result);
				return(false);
			}
			else{
				mygrid.setRowTextStyle(id, "color: red; ");
				mygrid.cells(id,8).setValue(1);
				mygrid.cells(id,9).setValue(0);
				$("#item_box").val('');
				setTimeout( function() { 
					  $("#item_box").focus(); 
					} , 500);
				if(global_item_reserved == 'y')
					ReserveQueue(item);
			}
			return;
		}
	});
}

//add reserve to the queue
function ReserveQueue(item){
	var result = new Array();
	var SQL = "select id_,forename_,surname_,borrower_ from reserves where status_='WAI' and catalogue_ = " + global_item_catalogue + " order by reserved_";  
	var SQLCOLS = "id_,forename_,surname_,borrower_"; 
	AjaxSql("item_box",SQL,SQLCOLS,result);		//results in result[i] etc
 	if(result[0] != '0'){
		alert("Please retain for borrower " + result[2] + " " + result[3] + "(" + result[4] + ")");
 		var SQL = "update reserves set " +
		"status_='COU' " +
		"where id_=" + result[1];
		var result = UpdateRecord(SQL,"item_box");
		if(isNaN(result)){
			alert(result);
			return(false)
		}
 	}
 }

//see if borrower has any reserves waiting
function ReserveCounter(_borrower){
	var result = new Array();
	var SQL = "select id_,catalogue_,title_ from reserves where status_ = 'COU' and borrower_ = " + _borrower;  
	var SQLCOLS = "id_,catalogue_,title_"; 
	AjaxSql("item_box",SQL,SQLCOLS,result);		//results in result[i] etc
	if(result[0] != '0')
		alert("Reserved item is waiting collection - " + result[3] + "(" + result[2] + ")");
}

//see if the issue is also on reserve and status COU
function ReserveIssue(_borrower,_item){
	var result = new Array();
	var SQL = "update reserves set status_ = 'CLA' where status_ = 'COU' and borrower_ = " + _borrower + " and item_ = " + _item;  
	var result = UpdateRecord(SQL,"item_box");
	if(isNaN(result)){
		alert(result);
		return(false);
	}
//another copy may be reserved
	var SQL = "select catalogue_ from reserves  where item_ = " + _item + " and (status_ = 'COU' or status_ = 'WAI')";   
	var SQLCOLS = "catalogue_"; 
	AjaxSql("item_box",SQL,SQLCOLS,result);		//results in result[i] etc
	if(result[0] == '0'){						//there is noone else in the queue
		var SQL = "update copies set reserved_ = '' where catalogue_ = " + global_item_catalogue;
		var result = UpdateRecord(SQL,"item_box");
		if(isNaN(result)){
			alert(result);
			return(false);
		}
	}
}

function DoRenew(_borrower,_item,_return,rId){
//override the return date if one has been entered manually
	if(global_renew_date != '')
		_return = global_renew_date;
	if(CheckRenewPriv('renews_',"renews",rId) == false)
		return;
	global_renew_date = '';
//	alert("renew " + _return);
	var _loan = 0;
	var _renew = 0;
	alert(global_item_renew);
	_loan = parseInt(global_item_loan,10) + 1;
	_renew = parseInt(global_item_renew,10) + 1;
	var SQL = "update copies set " +
			"borrower_='" + _borrower + "'," +
			"status_='LOA'," +
			"return_='" + SetDate(_return) + "'," +
			"overdue_=0," +
			"loan_=" + _loan + "," +
			"renew_=" + _renew + 
			" where barcode_='" + _item + "'";
	alert(SQL);
	var result = UpdateRecord(SQL,"item_box");
	if(isNaN(result)){
		alert(result);
		return(false)
	}
	mygrid.cells(rId,6).setValue(_renew);
	$("#item_box").val('');
	setTimeout( function() { 
		  $("#item_box").focus(); 
		} , 500);
	return(true);
}

function GoAccept(){	//scan each row for checked returns or renewals
	mygrid.forEachRow(function(id){
		var cellObj = mygrid.cellById(id, 0);
		var checked = mygrid.cells(id,8).getValue();
		if(checked == 1){		//checked for return
			var barcode = mygrid.cells(id,0).getValue();
			alert("barcode " + barcode + " id " + id);
			var SQL = "update copies set status_='SHE',renew_=0,overdue_=0 where barcode_ = '" + barcode + "'" 
			var result = UpdateRecord(SQL,"item_box");
			if(isNaN(result)){
				alert(result);
				return(false)
			}
			var rowID=mygrid.getRowId(id);
			alert("rowID " + rowID + " id " + id);
			mygrid.setRowColor(rowID,"red");
		}	
	});
}

function DoReserve(_borrower,_item){
	var result = new Array();
	var msg = global_item_title + 
	"(" + global_item_catalogue + "." + _item + ") is on loan to borrower " + 
	global_item_borrower + "  ---- Do you want to reserve it ?";
	var where = window.confirm(msg);
	if (where){
//see if any copies are on shelf
		var SQL = "select barcode_ from copies where status_ = 'SHE' and catalogue_=" +  global_item_catalogue;
		var SQLCOLS = "barcode_";
		AjaxSql("item_box",SQL,SQLCOLS,result);		//results in result[i] etc
		if(result[0] != '0'){
			alert("Not reserved. Copy " + result[1] + " is on the shelf");
			return(false);
		}
//set all the copies to reserved
		var SQL = "update copies set " +
		"reserved_='y' " +
		"where catalogue_=" + global_item_catalogue;
		var result = UpdateRecord(SQL,"item_box");
		if(isNaN(result)){
			alert(result);
			return(false)
		}
//add borrower to reserve queue
		var title = global_item_title;
		title = title.replace(/'/g,"\\'");
		title = title.replace(/"/g,"\"");
		title = title.replace(/\n/g,"");
		title = title.replace(/\r/g,"");

		var SQL = "insert into reserves(borrower_,catalogue_,item_,title_,reserved_,due_,surname_,forename_) " +
				"values('" +
				_borrower + "'," +
				global_item_catalogue + ",'" +
				_item + "','" +
				title + "','" +
				SetDate(GetDate()) + "','" +
				global_item_return + "','" +
		   		global_borrower_surname + "','" +
		   		global_borrower_forename + "'" +
				")";
		var result = InsertRecord(SQL);
		if(isNaN(result))
			alert(result);
		else{
			alert("Reserved");
			return(true);
		}
	}
	else{
		alert("Not reserved");
		return(false);
	}
}

function IssueMsg(a){
	var r = '';
	for(var i=2;i<a.length;i++){
		r += a[i];
		r += " ";
	}
	DeskMsg(r);
}

function DeskMsg(str){
	$("#trap_").text(str);
}

function QuickAddBorrowerClick(){
 	QuickBorrowerAdd('Quickly add a new borrower');
}

function QuickAddItemClick(){
 	QuickItemAdd('Quickly add a new item');
}

function QuickBorrowerAdd(myMessage){
	var ret = loadHtml("borrower_box","quickborrower.div");
	Tip(
	ret,CLICKSTICKY, true, CLICKCLOSE, false, 
	CLOSEBTN, true,SHADOW, true,	
	TITLE, myMessage, PADDING, 9,FIX, ['Welcome', 0, 5],
	WIDTH,560,FONTFACE, 'Arial, Helvetica, sans-serif', FONTSIZE, '10pt',TITLEALIGN, 'center');
	$("#quick_barcode_").bind("mousedown", function(e){
		if( e.button == 2 ) {  
	         clickCheck(this);  
	         return false;  
	       } else {  
	         eval(this);  
	         return(true);
	        }  
	    });
//	var z = document.getElementById("quick_category");
//	creatDbOptions(z,SQL_BORROWER_CATEGORY_LIST,"description_");
	$('label.required').append('&nbsp;<strong>*</strong>&nbsp;');
	GoToField("#quick_barcode_");
}
function GoQuickBorrowerSave(){
	var v = $("#quickForm").validate({
		errorClass: "warning",
		onkeyup: false,
		onblur: false,
		  onfocusout: false, 
		    onclick: false ,
		errorPlacement: function(error, element) { 
            offset = element.offset(); 
            error.insertBefore(element) 
            error.css('position', 'absolute'); 
            error.css('left', offset.left + element.outerWidth()); 
            error.css('top', offset.top); 
		}

	});
	var result = v.form();
	if(result == true){
//save borrower
		var SQL = $("#insert1").val();
		SQL += "'" + $("#quick_barcode_").val() + "',";
		SQL += "'" + $("#quick_forename_").val() + "',";
		SQL += "'" + $("#quick_surname_").val() + "',";
		SQL += "'Student')";
		var result = InsertRecord(SQL);
		if(isNaN(result))
			alert(result);
		else{
//save address
			var SQL = $("#insert2").val();
			SQL += "'" + $("#quick_barcode_").val() + "',";
			SQL += "'" + $("#quick_adr1_").val() + "',";
			SQL += "'y')";
			var result = InsertRecord(SQL);
			if(isNaN(result))
				alert(result);
			else{
				var SQL = $("#afterinsert").val();
				var barcode = $("#quick_barcode_").val();
				SQL = SQL.replace("$",barcode);
				UpdateRecord(SQL,"borrower_box");
				$("#borrower_box").val($("#quick_barcode_").val());
				UnTip();
				GoLocate();
			}
		}
	}
}

function QuickItemAdd(myMessage){
	var ret = loadHtml("item_box","quickitem.div");
	Tip(
	ret,CLICKSTICKY, true, CLICKCLOSE, false, 
	CLOSEBTN, true,SHADOW, true,	
	TITLE, myMessage, PADDING, 9,FIX, ['Welcome', 0, 5],
	WIDTH,560,FONTFACE, 'Arial, Helvetica, sans-serif', FONTSIZE, '10pt',TITLEALIGN, 'center');
	$("#quick_barcode_").bind("mousedown", function(e){
		if( e.button == 2 ) {  
	         clickCheck(this);  
	         return false;  
	       } else {  
	         eval(this);  
	         return(true);
	        }  
	    });
//	var z = document.getElementById("quick_category");
//	creatDbOptions(z,SQL_BORROWER_CATEGORY_LIST,"description_");
	$('label.required').append('&nbsp;<strong>*</strong>&nbsp;');
	GoToField("#quick_barcode_");
}

function GoQuickItemSave(){
	var v = $("#quickForm").validate({
		errorClass: "warning",
		onkeyup: false,
		onblur: false,
		  onfocusout: false, 
		    onclick: false ,
		errorPlacement: function(error, element) { 
            offset = element.offset(); 
            error.insertBefore(element) 
            error.css('position', 'absolute'); 
            error.css('left', offset.left + element.outerWidth()); 
            error.css('top', offset.top); 
		}

	});
	var result = v.form();
	if(result == true){
//save catalogue
		var SQL = $("#insert1").val();
		SQL += "'" + $("#quick_author_").val() + "',";
		SQL += "'" + $("#quick_title_").val() + "',";
		SQL += "'" + SetDate(GetDate()) + "')";
		var ret = InsertRecord(SQL);
		if(isNaN(ret))
			alert(ret);
		else{
//save copy
			var SQL = $("#insert2").val();
			SQL += "'" + $("#quick_barcode_").val() + "',";
			SQL += "'" + ret + "',";
			SQL += "'Ordinary','SHE','LRC','Main')";
			var ret = InsertRecord(SQL);
			if(isNaN(ret))
				alert(ret);
			else{
				var SQL = $("#afterinsert").val();
				var barcode = $("#quick_barcode_").val();
				SQL = SQL.replace("$",barcode);
				UpdateRecord(SQL,"item_box");
				$("#item_box").val($("#quick_barcode_").val());
				setTimeout( function() { 
					  $("#item_box").focus(); 
					} , 500);
				
				UnTip();

			}
		}
	}
}


function GoReset(){
	if($("#borrower_box").val() != ''){
		global_desk_state = '';
		mygrid.clearAll();
		$("#borrower_box").val('');
		$("#sindex_").val('');
		$("#item_box").val('');
		$("#title_").val('');
	}
	$("#trap_").text('');
	GoToField("#borrower_box");
}
function GoQuickReset(){
	if($("#item_box").val() == ''){
		global_desk_state = '';
		mygrid.clearAll();
		$("#item_box").val('');
		$("#title_").val('');
	}
	$("#trap_").text('');
	GoToField("#item_box");
}
function getElementWithFocus() {
	var hf;
	if ( document.activeElement ) 
		hf = document.activeElement;
	else 
		hf = document.focusNode;
	return hf;
}

//get an options list from a datbase
function creatDbOptions(z,SQL,thevalue){
	var optvalue = new Array();
	optvalue = thevalue.split('@@');
	GoPhpTable(SQL);
	for(var i = 0; i < XMLTABLE.length; i++){
		var opt = document.createElement("option");
		var e = XMLTABLE[i];
		var display = '';
		for(var j=0;j<optvalue.length;j++){
	  		display += e.getElementsByTagName(optvalue[j])[0].firstChild.data;
//	  		if(j < optvalue.length-1)
	//  			display += ':';
	  	}
	    opt.innerHTML = display;
		opt.value = display;
	    z.appendChild(opt);
	}
}

function GoCheckBox(rId,cInd,state){
alert("row " + rId + " col " + cInd + " state " + state);	
//update any renewalls
	var item = mygrid.cells(rId,0).getValue();
	if(cInd == 8)	//its a return
		DoReturn(item);
	else{
alert("checkbox global_renew_date " + global_renew_date);
		mygrid.forEachRow(function(id){
			if(mygrid.cells(id,9).getValue() == 1){
			alert("row " + id);
				var item = mygrid.cells(id,0).getValue();
			alert("item " + item);
				var item_category = mygrid.cells(id,2).getValue();
				var current_return_date = mygrid.cells(id,4).getValue();
				var renewdate = GetRenewDate(id,item,item_category,current_return_date);
				if(renewdate != ''){
					if(global_renew_date != '')
						renewdate = global_renew_date;
    			alert("checkbox renewdate " + renewdate);

        		mygrid.cells(id,4).setValue(renewdate);
					GetStatus(item);
					DoRenew($("#borrower_box").val(),item,renewdate,id);
					mygrid.cells(id,8).setValue(0);
					mygrid.setRowTextNormal(id);
				}
				else{
					mygrid.cells(id,8).setValue(1);
					mygrid.cells(id,9).setValue(0);
				}
			}
		});
	}
//	AcceptButton();
}


function AcceptButton(){
	if($('#accept_click').length == 0){
		var z = document.getElementById("groupholder");
		var img = document.createElement("img");
		img.setAttribute("id","accept_click");
		img.src = "images/accept.jpg";
		img.border = 0;
		img.title = "Accept the changes";
		addEvent(img, "click",function(){
			GoAccept();
		});		
		z.appendChild(img);
	}
}

function RenewAll(v){
	mygrid.forEachRow(function(id){
		var item = mygrid.cells(id,0).getValue();
		var item_category = mygrid.cells(id,2).getValue();
		var current_return_date = mygrid.cells(id,4).getValue();
		var renewdate = GetRenewDate(id,item,item_category,current_return_date);
		mygrid.cells(id,4).setValue(renewdate);
       	DoRenew($("#borrower_box").val(),item,renewdate,id);
       	mygrid.cells(id,8).setValue(0);
       	mygrid.cells(id,9).setValue(1);
       	mygrid.setRowTextNormal(id);
	});
	$("#renewall").attr('checked', false);
}

function ReturnAll(v){
	mygrid.forEachRow(function(id){
		var cellObj = mygrid.cellById(id, 0);
		var barcode = cellObj.getValue();
		mygrid.selectRowById(id);
		mygrid.cells(id,8).setValue(1);
		mygrid.cells(id,9).setValue(0);
		var barcode = mygrid.cells(id,0).getValue();
		var SQL = "update copies set status_='SHE',renew_=0,overdue_=0 where barcode_ = '" + barcode + "'" 
		var result = UpdateRecord(SQL,"item_box");
		if(isNaN(result)){
			alert(result);
			return(false);
		}
		else{
			mygrid.setRowTextStyle(id, "color: red; ");
			mygrid.cells(id,8).setValue(1);
			mygrid.cells(id,9).setValue(0);
			$("#item_box").val('');
			setTimeout( function() { 
				  $("#item_box").focus(); 
				} , 500);
			if(mygrid.cells(id,7).getValue() == 1)
				ReserveQueue(barcode);
		}
	});
	$("#returnall").attr('checked', false);

}
function DisableReserveColumn(){
	mygrid.forEachRow(function(id){
		mygrid.cells(id,7).setDisabled(true);
	});
}

function GetRenewDate(row,item,item_category,current_return_date){
	var reserved_rows = new Array();
	var use_this_date = '';
	if(item_category == ''){
		alert(item + " has no lending category: using ordinary");
		item_category = 'ordinary';
	}
//check that this item is not reserved
	if(mygrid.cells(row,7).getValue() == 1){
			alert(item + " is reserved");
			return('');
	}
		
//first level check get loan period and return date from category matrix
	var SQL = SQL_CATEGORY_MATRIX;
	SQL = SQL.replace('$borrower',global_borrower_category);
	SQL = SQL.replace('$item',item_category);
//prompt("matrix",SQL);
	var matrix_return = RenewCalc("Matrix",SQL);
//alert("matrix return " + matrix_return);
	var SQL = SQL_BORROWER_CATEGORY_RETURN;
	SQL = SQL.replace('$category',global_borrower_category);
//prompt("borrower category",SQL);
	var borrower_category_return = RenewCalc("Borrower",SQL);
//alert("borrower category return " + borrower_category_return);

	var SQL = SQL_ITEM_CATEGORY_RETURN;
	SQL = SQL.replace('$category',item_category);
//prompt("item category",SQL);
	var item_category_return = RenewCalc("Item",SQL);
//alert("item" + item_category_return);

//hierarchy of dates
//holiday date
//matrix date
//book category
//borrower	category
//get any return date from special dates
	if(matrix_return != '')
		use_this_date = GetSpecial(matrix_return);
	else if(item_category_return != '')
		use_this_date = GetSpecial(item_category_return);
	else if(borrower_category_return != '')
		use_this_date = GetSpecial(borrower_category_return);
	return(use_this_date);
}

function CalcReturnDate(){
	var reserved_rows = new Array();
	var use_this_date = '';
	if(global_item_category == ''){
		alert($("#item_box").val() + " has no lending category: using ordinary");
		global_item_category = 'ordinary';
	}
	
//first level check get loan period and return date from category matrix
	var SQL = SQL_CATEGORY_MATRIX;
	SQL = SQL.replace('$borrower',global_borrower_category);
	SQL = SQL.replace('$item',global_item_category);
//prompt("matrix",SQL);
	var matrix_return = RenewCalc("Matrix",SQL);
//alert("matrix return " + matrix_return);
	var SQL = SQL_BORROWER_CATEGORY_RETURN;
	SQL = SQL.replace('$category',global_borrower_category);
//prompt("borrower category",SQL);
	var borrower_category_return = RenewCalc("Borrower",SQL);
//alert("borrower category return " + borrower_category_return);

	var SQL = SQL_ITEM_CATEGORY_RETURN;
	SQL = SQL.replace('$category',global_item_category);
//prompt("item category",SQL);
	var item_category_return = RenewCalc("Item",SQL);
//alert("item" + item_category_return);

//hierarchy of dates
//holiday date
//matrix date
//book category
//borrower	category
//get any return date from special dates
	if(matrix_return != '')
		use_this_date = GetSpecial(matrix_return);
	else if(global_item_category != '')
		use_this_date = GetSpecial(item_category_return);
	else if(borrower_category_return != '')
		use_this_date = GetSpecial(borrower_category_return);
	return(use_this_date);
 }


function GetSpecial(d){
	var a = new Array();
	a = d.split("/");
	var myreturn = a[2] + "-" + a[1] + "-" + a[0];
	var SQL = SQL_SPECIAL_DATE;
	SQL = SQL.replace('$myreturn',myreturn);
	SQL = SQL.replace('$myreturn',myreturn);
//prompt("",SQL);
	var result = new Array();
	var SQLCOLS = "return_";
	AjaxSql("item_box",SQL,SQLCOLS,result);		//results in result[i] etc
//alert("result " + result);
	if(result[0] == 0)
		myreturn = d;
	else{
		var a = new Array();
		a = result[1].split("-");
		var myreturn = a[0] + "/" + a[1] + "/" + a[2];
	}
//	alert(myreturn);
	return(myreturn);
}

function RenewCalc(renewtype,SQL){ 
//	alert(renewtype);
	var result = new Array();
	var SQLCOLS = "period_,return_";
//	prompt("matrix",SQL);
  	AjaxSql("item_box",SQL,SQLCOLS,result);		//results in result[i] etc
	if(result[0] == 0)
		return('');
	var _return = result[2];
	var _period = result[1];
//return date is priority
	if(_return == "0000-00-00"){
  		if(_period != '')
  			_return = GetReturnDate(_period);
  		else{
  			alert("Return date: invalid category data")
  			_return = GetReturnDate(0);
  		}
  	}
  	else{
		var a = new Array();
		a = result[2].split('-');
  		_return = a[2] + "/" + a[1] + "/" + a[0];
  		
  	}
//	alert(_return);
	return(_return);
}

 //calculate a new date from a period
 function GetReturnDate(period){
	var newdue = '';
	var due = new Date();
	due.addBusDays(+period);
	newdue += due.getDate(); 
	newdue +=  "/"; 
	newdue += due.getMonth()+1; 
	newdue += "/"; 
	newdue += due.getFullYear();
	return(newdue);
}
 
function AjaxSql(fieldname,SQL,SQLCOLS,result){
	var COLS_ARRAY = SQLCOLS.split(',');
	$.ajax({
	   	method: "get",url: "gophptable.php",data:"cmd=" + SQL,
	   	async: false,
	beforeSend: function(){
		$("#load_" + fieldname).html('<img src="/images/wait.gif" />');
      	$("#load_" + fieldname).show("fast");
   	},
    complete: function(){ 
		$("#load_" + fieldname).html('');
   		$("#load_" + fieldname).hide("slow");
   	},
	    success: function(data){
	   		var xml;
	   		if($.browser.msie){
	   			if (typeof data == "string") {
	   				xml = new ActiveXObject("Microsoft.XMLDOM");
	   				xml.async = false;
	   				xml.loadXML(data);
	   			} else {
	   				xml = data;
	   			}
	   		}
	   		else 
	   			xml = data;
//count number of records
	   		result[0] = 0;
	   		var i = 1;
	   		$(xml).find('record').each(function(x){
	   				
	   				for(var j=0;j<COLS_ARRAY.length;j++){
	   					var myData = $(this).find(COLS_ARRAY[j]).text();
	   					if(myData == 'empty')
	   						myData = '';
   						result[i] = myData;
   						i++;
	   				}
	   				result[0] += 1;
	   		});
	   	}
	});
}

function GoBorrowerAuthority(fieldname,header,phpfile,seed,popit,multi,finder){
	var copyfrom='';
	var ihtml=	"<div>Please choose the correct term</div>" +
	"	<div id=\"combo\" style=\"width:200px; height:15px;\"></div>";
	var myValue = $(popit).val();
	if(myValue != ''){		//see if there is a valid entry already in the box
		GoLocate();
	}
	else{
		Tip(
		ihtml,CLICKSTICKY, true, CLICKCLOSE, false, 
		CLOSEBTN, true,	
		TITLE, header + ' Authority', PADDING, 9,FIX, [570, 300],
		WIDTH,400,FONTFACE, 'Arial, Helvetica, sans-serif', FONTSIZE, '10pt',TITLEALIGN, 'center');
		var z = new dhtmlXCombo("combo", "alfa", 400);
		z.enableFilteringMode(true, phpfile, true, true);
		z.setComboText(seed);
		z.setOptionHeight(300);
		if(finder != '')		//see if there is a valid entry already in the box
			copyfrom = $("#copyfrom").val();
		z.attachEvent("onChange", function(value,state){BorrowerPop(z,3);});
	}
}

function BorrowerPop(z,pick){
	var myValue = z.getComboText();
	var pos = myValue.indexOf('---');
	if(pos != -1){
		if(pick == '')
			pick = 0;
		myValue = myValue.split("---")[pick];
		
	}
	else if(!isNaN(pick)){
		var x = z.getComboText().split('\t');
		myValue = x[pick];
	}
	$("#borrower_box").val(myValue);
	GoLocate();
	UnTip();
}

function GoItemAuthority(fieldname,header,phpfile,seed,popit,multi,finder){
	var copyfrom1='';
	var ihtml=	"<div id=\"combo\" style=\"width:200px; height:15px; text-align:left;\"></div>";
	var myValue = $(popit).val();
	if(myValue != ''){		//see if there is a valid entry already in the box
		GoLocate();
	}
	else{
		Tip(
		ihtml,CLICKSTICKY, true, CLICKCLOSE, false, 
		CLOSEBTN, true,	
		TITLE, header + ' Authority', PADDING, 9,FIX, [570, 300],
		WIDTH,400,FONTFACE, 'Arial, Helvetica, sans-serif', FONTSIZE, '10pt',TITLEALIGN, 'center');
		var z = new dhtmlXCombo("combo", "alfa", 400);
		z.enableFilteringMode(true, phpfile, true, true);
		z.setComboText(seed);
		z.enableOptionAutoPositioning(true);
		z.setOptionHeight(300);
		if(finder != '')		//see if there is a valid entry already in the box
			copyfrom1 = $("#copyfrom1").val();
		z.attachEvent("onChange", function(value,state){ItemPop(z,1);});
	}
}
function ItemPop(z,pick){
	var myValue = z.getComboText();
	var pos = myValue.indexOf('---');
	if(pos != -1){
		if(pick == '')
			pick = 0;
		myValue = myValue.split("---")[pick];
		
	}
	else if(!isNaN(pick)){
		var x = z.getComboText().split('\t');
		myValue = x[pick];
	}
//now see if we have more than one catalogue record  	
	var title = myValue;
	title = title.replace(/'/g,"\\'");
	title = title.replace(/"/g,"\"");
	title = title.replace(/\n/g,"");
	title = title.replace(/\r/g,"");
  	var SQL = "select count(title_) as nrecords from catalogue where title_ = '" + title + "'";
  	var SQLCOLS = "nrecords";
	var result = new Array();
  	AjaxSql("item_box",SQL,SQLCOLS,result);		//results in result[i] etc
	if(result[1] > 1){
		alert("More than one catalogue record: ambiguous barcode");
		return;
	}
//now see if we have more than one copy
	var id = myValue;
	var SQL = "select barcode_ from copies where catalogue_ = " + id;
  	var SQLCOLS = "barcode_";
	var result = new Array();
	AjaxSql("item_box",SQL,SQLCOLS,result);		//results in result[i] etc
	if(result[0] == 0){
		alert("No Barcode attached to this title");
		return;
	}	
	if(result[0] > 1){
		alert("More than one copy: ambiguous barcode");
		return;
	}	

	$("#item_box").val(result[1]);
	GoLocate();
	UnTip();
}

function loadHtml(fieldname,filename)
{
	var ret = '';
		$.ajax(
        {
        	method: "get",url: "gophpform.php",data: "filename=" + filename, 
    	   	async: false,
    	   	beforeSend: function(){
    		$("#load_" + fieldname).html('<img src="/images/wait.gif" />');
          	$("#load_" + fieldname).show("fast");
       	},
        complete: function(){ 
    		$("#load_" + fieldname).html('');
       		$("#load_" + fieldname).hide("slow");
       	},
          success: function(html) 
            {	
               ret = html;
            }
        });			        
		return(ret);
}

function GoNextQuickMember(){
   	$.ajax({
   	   	method: "get",url: "nextmemberbarcode.php",
   	   	async: false,
   	   	beforeSend: function(){
   			$('#load_quick_barcode').html('<img src="/images/wait.gif" />');
   	      	$("#load_quick_barcode").show("fast");
   	   	},
   	    complete: function(){ 
   			$('#load_quick_barcode').html('');
   	   		$("#load_quick_barcode").hide("slow");
   	   	},
   	    success: function(data){
   	   		var xml;
   	   		if($.browser.msie){
   	   			if (typeof data == "string") {
   	   				xml = new ActiveXObject("Microsoft.XMLDOM");
   	   				xml.async = false;
   	   				xml.loadXML(data);
   	   			} 
   	   			else
   	   				xml = data;
   	   		}
        	else 
        		xml = data;
        	$(xml).find('record').each(function(x){
        	   	var myData = $(this).find("barcode").text();
        		$("#quick_barcode_").val(myData);
        	});
   	   	},
   	   	error: function(){
   	   		alert('here');
   	   	}
    });

}
function GoNextQuickItem(){
   	$.ajax({
   	   	method: "get",url: "nextbarcode.php",
   	   	async: false,
   	   	beforeSend: function(){
   			$('#load_quick_barcode').html('<img src="/images/wait.gif" />');
   	      	$("#load_quick_barcode").show("fast");
   	   	},
   	    complete: function(){ 
   			$('#load_quick_barcode').html('');
   	   		$("#load_quick_barcode").hide("slow");
   	   	},
   	    success: function(data){
   	   		var xml;
   	   		if($.browser.msie){
   	   			if (typeof data == "string") {
   	   				xml = new ActiveXObject("Microsoft.XMLDOM");
   	   				xml.async = false;
   	   				xml.loadXML(data);
   	   			} 
   	   			else
   	   				xml = data;
   	   		}
        	else 
        		xml = data;
        	$(xml).find('record').each(function(x){
        	   	var myData = $(this).find("barcode").text();
        		$("#quick_barcode_").val(myData);
        	});
   	   	},
   	   	error: function(){
   	   		alert('here');
   	   	}
    });

}
function loadIssueTab(div,filename)
{
		$.ajax(
        {
        	method: "get",url: "gophpform.php",data: "filename=" + filename, 
        	async: false,
     	   	beforeSend: function(){
			$("#tab").html('<img src="/images/wait.gif" />');
	      	$("#tab").show("fast");
	   	},
	    complete: function(){ 
			$("#tab").html('');
	   		$("#tab").hide("slow");
	   	},
           success: function(html) 
            {			    
                $(div).append(html); 
            }
        });			        
}
function IssueSetMouseKeys(){
	$(document)[0].oncontextmenu = function() {return false;}  
	$("#borrower_box").bind("mousedown", function(e){
		if(e.button == 2){  
	 		GoBorrowerAuthority('sindex_','Borrowers','loadborrower.php','%','#borrower_box',false,'copyfrom'); 
			return false;  
		} 
		else  
			return true;    
    });
	$("#item_box").bind("mousedown", function(e){
		if(e.button == 2){  
			GoItemAuthority('title_','Title','loadtitle.php','a','#item_box',false,'copyfrom1');
			return(false);
		} 
		else  
			return true;    
    });
}

function IssueclickCheck(e){
	var a = $($(e)).text();
	var b = $($(e)).attr("class");

}

function IssuecheckForEnter (event) {
    if (event.keyCode == 13) {
    	event.preventDefault();
    	return false;
	}
} 