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_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_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_borrower_fines = '';
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 global_item_site = '';
var global_item_short = '';
var global_item_class = '';
var global_borrower_dept = '';
var global_borrower_course = '';
var global_borrower_tutor = '';
var global_borrower_charge = '0.00';
var global_item_fine = '0.00';
var global_trap_message = '';
var global_nextrow = 0;
var global_nextrowArray = new Array();
var mygrid;
var global_ret = false;
Number.prototype.mod = function(n) {
return ((this%n)+n)%n;
};

Date.prototype.addBusDays = function(dd) {
//	alert("period " + dd);
	var wks = Math.floor(dd/5);
	var dys = dd.mod(5);
//	alert("dys " + dys);
	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('850px','260px');
	loadIssueTab("#workbar","m120.div");
	IssueSetMouseKeys();
	global_nextrow = 0;
	$('#borrower_box').bind('keypress', function(e) { 
        if(e.keyCode==13){
        	if($("#borrower_box").val() == ''){
        		GoToField("#item_box"); 
            	e.preventDefault();
        	}
        	else{
        		global_desk_state = '';
        		global_renew_date = '';
        		InitArray(global_nextrowArray);
        		global_nextrow = 0;
        		mygrid.clearAll();
        		GoLocate();
        		e.preventDefault();
        	}
        } 
	});
	$('#borrower_box').bind('click', function(e) { 
		global_desk_state = '';
		global_renew_date = '';
		mygrid.clearAll();
		e.preventDefault();
	});

	$('#item_box').bind('keypress', function(e) { 
       if(e.keyCode==13){
        	if($("#item_box").val() == ''){
        		GoReset();
        		GoToField("#borrower_box");
            	e.preventDefault();
        	}
        	else
        		GoLocate();
        	e.preventDefault();
        } 
       else if(e.keyCode==40){
    	   if(global_nextrow == global_nextrowArray.length){
    		   	global_nextrow = 0;
       			$('#item_box').val('');
    	   }
    	   else{
    		   	$('#item_box').val( global_nextrowArray[global_nextrow]);
       			global_nextrow++;
    	   }
    	   e.preventDefault();
        } 
	});

	GoIssueDesk();
	mygrid.attachEvent("onXLE",	function(){
		DisableReserveColumn();
		var tf = AddFines();
		if(tf != 0 && tf != '')
			$("#currentfine_").text("Current Fine: " + tf);
		else
			$("#currentfine_").text('');
		mygrid.forEachRow(function(id){		
	  		cellObj = mygrid.cellById(id, 0);
	  		var barcode = cellObj.getValue();
	   		global_nextrowArray.push(barcode);
	  	});
	});
	$('#click_movie').bind('click', function() {
		 GoVideo("circulation.mov");
		});
}

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('@@');
   		$("#ctitle_").val(x[0] + " " + x[1] + " " +  x[2] + " " + result[5]);
		if(result[3] != '' || result[4] != ''){
			$("#trap").css("color", "red"); 
			$("#trap_").text(result[3] + "  " + result[4]);
		}
		if(result[12] > 0)
			$("#currentfine_").text(result[12]);
		if(result[13] > 0)
			$("#charges_").text(result[13]);
	 	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 GoQuickReset(){
	if($("#item_box").val() == ''){
		global_desk_state = '';
		$("#item_box").val('');
	}
	$("#currentfine_").text('');
	$("#heldfine_").text('');
	$("#charges_").text('');
	$("#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.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,285,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();
	global_mygrid = mygrid;
	mygrid.enableColumnAutoSize(true);
	mygrid.attachEvent("onCheckbox",function(rId,cInd,state) {GoCheckBox(rId,cInd,state);});
	mygrid.attachEvent("onEnter",function(rowId,columnIndex){
		if(columnIndex == 4){
			global_renew_date  = mygrid.cells(rowId,columnIndex).getValue();
		}
	});
	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_";
	global_today = GetServerDate(SQL);
	var _borrower = $("#borrower_box").val();
	var _item = $("#item_box").val();
//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
		_status = GetStatus(_item);			//get item _status
		if(OnLoan(_borrower,_item))				//if item on loan to this borrower
			DoReturn(_item);							//return the item
		else {
			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');
		}
	}
	global_renew_date = '';
}

//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('@@');
  		global_borrower_fines = result[4];
  		global_borrower_charge = result[5];
   		global_borrower_category = result[3];
   		global_borrower_ceiling = GetCeiling(result[3]);
   		global_borrower_surname = x[0];
   		global_borrower_forename = x[1];
		$("#sindex_").val(x[1] + " " + x[0] + " " +  x[2] + " " +  x[4] + " " + result[3]);
		if(result[4] != 0 && result[4] != '')
			$("#heldfine_").text("Held fines: " + result[4]);
		else
			$("#heldfine_").text('');
		if(result[5] != 0 && result[5] != '')		
			$("#charges_").text("Charges: " + result[5]);
		else
			$("#charges_").text('');
		if(result[2] != '')
			$("#trap_").text("Messages: " + result[2]);
		else
			$("#trap_").text('');
		var v = $("#borrower_box").val();
 //get the loans
		var SQL = SQL_ISSUED_TO_BORROWER; 
		SQL = SQL.replace('$borrower',v);
		mygrid.loadXML("connector.php?cmd="+SQL+"&cols=" + SQL_ISSUED_TO_BORROWER_COLS + "&");
		GoToField("#item_box");
	 	ReserveCounter(v);
   	}
  	else{	//now check surnames
  		DeskMsg("Unknown Borrower");
  		$("#borrower_box").val('');
 		GoBorrowerAuthority('sindex_','Borrowers','loadborrower.php',v,'#borrower_box',false,'copyfrom'); 
 //		QuickBorrowerAdd('Quickly add a new borrower');
	}
 //	var count=mygrid.getRowsNum();
 //	alert("count " + count);
 //	var ids=mygrid.getAllRowIds();
 //	alert("ids " + ids);
 	
}

function AddFines(){
	var totalfine=0;
	mygrid.forEachRow(function(id){
		if(mygrid.cells(id,5).getValue() > 0)
			totalfine += parseFloat(mygrid.cells(id,5).getValue());
	});	
	if(totalfine > global_borrower_ceiling)
		totalfine = global_borrower_ceiling;
	return(totalfine);
}

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
 //  	alert("get status " + result);
 	if(result[0] != '0'){		//number is valid
  		var x = result[1].split('@@');
   		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];
		$("#ctitle_").val(x[0] + " " + x[1] + " " +  x[2] + " " + result[5]);
		if(result[3] != '' || result[4] != ''){
			$("#trap_").text(result[3] + " : " + result[4]);
			$("#trap").css("color", "red"); 
		}

		return(_status);
 	}
  	else{
  		DeskMsg("Unknown Item");
 		QuickItemAdd('Quickly add a new item');
	}
 	return('NEW');
}
function GetCeiling(bcat){			//get the fine ceiling for this category
	var result = new Array();
	var SQL = "select ceiling_ from borrower_category where category_ = '" + bcat + "'";
	var SQLCOLS = "ceiling_";
   	AjaxSql("item_box",SQL,SQLCOLS,result);		//results in result[i] etc
 	if(result[0] != '0'){		//number is valid
  		return(result[1]);
 	}
  	else{
  		DeskMsg("Unknown Category");
  		return('0.00');
  	}
}



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){
//	alert("doissue");
	ingid = false;
	var rowCnt = 0;
	if(CheckMyPriv('circulation:iss.x.x.x') == false){
		$("#messages").text("No privilege for issue please login");
		return;
	}
	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);
	}
//	alert("log");
	DoloanLog(_borrower,global_borrower_surname + " " + global_borrower_forename,_item,global_item_title,"LOA",SetDate(global_today),GetTime(),global_item_fine,global_borrower_category,global_item_category,global_item_class,global_borrower_dept,global_borrower_course,global_borrower_tutor,global_borrower_charge,global_item_short,global_item_site);
	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 + " (" + matrixLoans + ")" + " 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){
	if(CheckMyPriv('circulation:x.ret.x.x') == false){
		$("#messages").text("No privilege for return please login");
		return;
	}
	mygrid.forEachRow(function(id){
		var cellObj = mygrid.cellById(id, 0);
		var barcode = cellObj.getValue();
		if(barcode == item){
			if(mygrid.cells(id,5).getValue() > 0){
				HandleFine(mygrid.cells(id,5).getValue(),mygrid,id);
			}
			else{
				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,fine_ = 0 where barcode_ = '" + barcode + "'";
				var result = UpdateRecord(SQL,"item_box");
				if(isNaN(result)){
					alert("DoReturn:" + SQL + ":" + result);
				}
				else{
					mygrid.setRowTextStyle(id, "color: red; ");
					mygrid.cells(id,8).setValue(1);
					mygrid.cells(id,9).setValue(0);
					GoToField("#item_box");
					if(global_item_reserved == 'y')
						ReserveQueue(item);	
					DoloanLog($("#borrower_box").val(),global_borrower_surname + " " + global_borrower_forename,barcode,global_item_title,"SHE",SetDate(global_today),GetTime(),global_item_fine,global_borrower_category,global_item_category,global_item_class,global_borrower_dept,global_borrower_course,global_borrower_tutor,global_borrower_charge,global_item_short,global_item_site);
				}
			}	
		}
	});
	$("#item_box").val('');
	GoToField("#item_box");
}

//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(CheckMyPriv('circulation:x.x.ren.x') == false){
		$("#messages").text("No privilege for renewal please login");
		return;
	}
	if(global_renew_date != '')
		_return = global_renew_date;
	if(CheckRenewPriv('renews_',"renews",rId) == false)
		return;
	global_renew_date = '';
//	alert("renew AT" + _return);
	var _loan = 0;
	var _renew = 0;

	_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);
	DoloanLog(_borrower,global_borrower_surname + " " + global_borrower_forename,_item,global_item_title,"REN",SetDate(global_today),GetTime(),global_item_fine,global_borrower_category,global_item_category,global_item_class,global_borrower_dept,global_borrower_course,global_borrower_tutor,global_borrower_charge,global_item_short,global_item_site);

	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){
	if(CheckMyPriv('circulation:x.x.x.res') == false){
		$("#messages").text("No privilege for reserve please login");
		return;
	}
	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);
		}
	DoloanLog(_borrower,global_borrower_surname + " " + global_borrower_forename,_item,global_item_title,"RES",SetDate(global_today),GetTime(),global_item_fine,global_borrower_category,global_item_category,global_item_class,global_borrower_dept,global_borrower_course,global_borrower_tutor,global_borrower_charge,global_item_short,global_item_site);
//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");
			$("#item_box").val('');
			GoToField("#item_box");
			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").css("color", "red"); 
	$("#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 += "'Staff')";
		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 += "'Home')";
			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 = '';
		global_renew_date = '';
		mygrid.clearAll();
		$("#borrower_box").val('');
		$("#sindex_").val('');
		$("#item_box").val('');
		$("#ctitle_").val('');
		
	}
	$("#currentfine_").text('');
	$("#heldfine_").text('');
	$("#charges_").text('');
	$("#trap_").text('');
	GoToField("#borrower_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);
	//			alert("renewdate " + renewdate);
				if(renewdate != ''){
	//				alert("global renewdate " + global_renew_date);
					if(global_renew_date != '' && global_renew_date != '00/00/0000')
						renewdate = global_renew_date;
					mygrid.cells(id,4).setValue(renewdate);
				}
    		//	alert("checkbox renewdate " + renewdate);
				else
					mygrid.cells(id,4).setValue(current_return_date);
				GetStatus(item);
				DoRenew($("#borrower_box").val(),item,renewdate,id);
				mygrid.cells(id,8).setValue(0);
				mygrid.setRowTextNormal(id);
			}
		});
	}
//	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);
	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);
	if(use_this_date == ''){
		alert("Unable to calculate renew date , check categories");
		return("00/00/0000");
	}
	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);
//	alert("use " + use_this_date);
	if(use_this_date == ''){
		alert("Unable to calculate renew date , check categories");
		return("00/00/0000");
	}
	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("renewcalc ",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("renewcalc " + _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 ESQL = escape(SQL);
	var COLS_ARRAY = SQLCOLS.split(',');
	$.ajax({
	   	method: "get",url: "gophptable.php",data:"cmd=" + ESQL,
	   	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('@@');
		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('@@');
		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();
	GoToField("#item_box");
}

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('Error');
   	   	}
    });

}
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('Error');
   	   	}
    });

}
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;
	}
} 


function GoBorrowerHistory(){
	var borrower_ = $("#borrower_box").val();
	if(borrower_ == ''){
		alert("Enter a borrower id");
    		GoToField("#borrower_box");
		return;
	}
	var dhxWins,w1,	tabbar;
	dhxWins = new dhtmlXWindows();
    	dhxWins.enableAutoViewport(true);
    	dhxWins.setImagePath("imgs/");
    	w1 = dhxWins.createWindow("w1", 100, 100, 800,400);
 	w1.setText("Borrower History: " + borrower_);
	global_window = w1;
	w1.setModal(false);
  
	myhistorygrid = w1.attachGrid();
	var SQL = "select borrower_,name_,barcode_,title_,transact_,tdate_,ttime_,site_ from loanlog where " + 	"borrower_ = '" + borrower_ + "'";
	var SQLCOLS = "borrower_,name_,barcode_,title_,transact_,tdate_,ttime_,site_";
	
	myhistorygrid.setHeader("Borrower,Name,Barcode,Title,Transaction,Date,Time,Site"); 
	myhistorygrid.setInitWidths("70,90,70,215,90,70,70,70"); 
	myhistorygrid.setColTypes("ro,ro,ro,ro,ro,ro,ro,ro");
	myhistorygrid.setColAlign("left,left,left,left,left,left,left,left"); 
	myhistorygrid.setColSorting("connector,connector,connector,connector,connector,connector,connector,connector");
	myhistorygrid.attachEvent("onXLE", function() {
		showLoading(false);
	});
   	myhistorygrid.attachEvent("onXLS", function() {
        	showLoading(true);
    	});
	dhxWins.attachEvent("onClose", function(win){
		GoToField("#borrower_box");
		return true; 
    	});
 	myhistorygrid.setImagePath("imgs/");
 	myhistorygrid.setSkin("light"); 
	myhistorygrid.init();
	myhistorygrid.enableColumnAutoSize(true);
//	myhistorygrid.enablePaging(true,50,10,"pagingarea",true);
//	myhistorygrid.setPagingSkin("bricks");
	myhistorygrid.loadXML("connector.php?cmd="+SQL+"&cols="+SQLCOLS+"&");
}
   
function GoItemHistory(){
	var item_ = $("#item_box").val();
	if(item_ == ''){
		alert("Enter an Item barcode");
    		GoToField("#item_box");
		return;
	}
	var dhxWins,w1,	tabbar;
	dhxWins = new dhtmlXWindows();
    	dhxWins.enableAutoViewport(true);
    	dhxWins.setImagePath("imgs/");
    	w1 = dhxWins.createWindow("w1", 100, 100, 800,400);
 	w1.setText("Item History: " + item_);
	global_window = w1;
	w1.setModal(true);
	myhistorygrid = w1.attachGrid();
	var SQL = "select barcode_,title_,borrower_,name_,transact_,tdate_,ttime_,site_ from loanlog where " + "barcode_ =  '" + item_ + "'";
	var SQLCOLS = "barcode_,title_,borrower_,name_,transact_,tdate_,ttime_,site_";
	myhistorygrid.setHeader("Barcode,Title,Borrower,Name,Transaction,Date,Time,Site"); 
	myhistorygrid.setInitWidths("70,215,70,90,90,70,70,70"); 
	myhistorygrid.setColTypes("ro,ro,ro,ro,ro,ro,ro,ro");
	myhistorygrid.setColAlign("left,left,left,left,left,left,left,left"); 
	myhistorygrid.setColSorting("connector,connector,connector,connector,connector,connector,connector,connector");
	myhistorygrid.attachEvent("onXLE", function() {
		showLoading(false);
	});
   	myhistorygrid.attachEvent("onXLS", function() {
        	showLoading(true);
    	});
	dhxWins.attachEvent("onClose", function(win){
		GoToField("#item_box");
		return true; 
    	});
 	myhistorygrid.setImagePath("imgs/");
 	myhistorygrid.setSkin("light"); 
	myhistorygrid.init();
	myhistorygrid.enableColumnAutoSize(true);
//	myhistorygrid.enablePaging(true,50,10,"pagingarea",true);
//	myhistorygrid.setPagingSkin("bricks");
	myhistorygrid.loadXML("connector.php?cmd="+SQL+"&cols="+SQLCOLS+"&");
}

function GetTime(){
	var currentTime = new Date();
	var hours = currentTime.getHours();
	var minutes = currentTime.getMinutes();
	if (minutes < 10){
		minutes = "0" + minutes;
	}
	return(hours + ":" + minutes);
}

function DoloanLog(borrower,surname,barcode,title,transact,tdate,ttime,fine,bcat,kcat,cclass,depart,course,tutor,charge,short,site){
	var SQL = "insert into loanlog(borrower_,name_,barcode_,title_,transact_,tdate_,ttime_,fine_,bcat_,kcat_,class_,depart_,course_,tutor_,charge_,short_,site_)";
	SQL += "values(" +
	"'" + borrower + "'" +
	",'" + surname.replace("'","''") + "'" +
	",'" + barcode + "'" +
	",'" + title.replace("'","''") + "'" +
	",'" + transact + "'" +
	",'" + tdate + "'" +
	",'" + ttime + "'" +
	",'" + fine + "'" +
	",'" + bcat + "'" +
	",'" + kcat + "'" +
	",'" + cclass + "'" +
	",'" + depart + "'" +
	",'" + course + "'" +
	",'" + tutor + "'" +
	",'" + charge + "'" +
	",'" + short + "'" +
	",'" + site + "')";
	var result = InsertRecord(SQL);
	if(isNaN(result))
		alert(result);
}

function DofineLog(borrower,surname,barcode,title,transact,tdate,ttime,fine){
	var SQL = "insert into fines(borrower_,name_,barcode_,title_,transact_,tdate_,ttime_,fine_)";
	SQL += "values(" +
	"'" + borrower + "'" +
	",'" + surname.replace("'","''") + "'" +
	",'" + barcode + "'" +
	",'" + title.replace("'","''") + "'" +
	",'" + transact + "'" +
	",'" + tdate + "'" +
	",'" + ttime + "'" +
	",'" + fine + "'" + ")";
	var result = InsertRecord(SQL);
	if(isNaN(result))
		alert(result);
}

function GoBorrowerTrap(){
	var borrower_ = $("#borrower_box").val();
	if(CheckMyPriv('manage:x.c.x.x') == false){
		$("#messages").text("No privilege for adding trap please login");
    		GoToField("#borrower_box");
		return;
	}
	if(borrower_ == ''){
		alert("Enter a borrower id");
    		GoToField("#borrower_box");
		return;
	}
	var dhxWins,w1,	tabbar;
	dhxWins = new dhtmlXWindows();
    	dhxWins.enableAutoViewport(true);
	dhxWins.setImagePath("imgs/");
	w1 = dhxWins.createWindow("w1", 100, 100, 650,300);
	global_window = w1;
	dhxWins.attachEvent("onClose", function(win){
			var x = $("#borrower_box").val();
	  	
		m120();
			$("#borrower_box").val(x);
			GoLocate();
			GoToField("#borrower_box");
		return true; 
		});

    	w1.setText("Enter record: m49717.xml");
	w1.setModal(true);
    	tabbar = w1.attachTabbar();
    	tabbar.setSkin("dhx_skyblue");
    	tabbar.setImagePath("imgs/");
    	tabbar.attachEvent("onXLE", function() { //row_id will be the first row
    		showLoading(false);
        	SetMouseKeys();
    		SetValidator();
    		MakeDisableOnNew();
    		GoToField("#message_");
	});
	tabbar.attachEvent("onXLS", function() {
        	showLoading(true);
    	});
    	tabbar.loadXML("m49717.xml");
}

function GoNotBorrowerTrap(){
		var SQL = "update members set trap_ = " + "''" + " where members.barcode_ = " + "'" + $("#borrower_box").val() + "'";
		var result = UpdateRecord(SQL,"tab");
		if(isNaN(result)){
			alert(result);
			return;
		}
		$("#trap_").text('');

}

function GoNewBorrowerTrap(){
	if($("#message_").val() != '' && $("#id_").val() == ''){
		var SQL = "insert into traps(trap_) values('" + $("#message_").val() + "')";
		var result = InsertRecord(SQL,"tab");
		if(!isNaN(result))
			$("#id_").val(result);
		var SQL = "update members set trap_ = " + "'" +$("#message_").val() + "'" + " where members.barcode_ = " + "'" + $("#borrower_box").val() + "'";
		var result = UpdateRecord(SQL,"tab");
		if(isNaN(result)){
			alert(result);
			GoToField("#message_");
			return;
		}
		$("#trap").css("color", "red"); 
		$("#trap_").text($("#message_").val());
		global_trap_message = $("#message_").val();
		global_window.setText("Record Saved");
	}
	else
		GoToField("#message_");
	
}

function GoItemTrap(){
	var item_ = $("#item_box").val();
	if(CheckMyPriv('manage:x.c.x.x') == false){
		$("#messages").text("No privilege for adding trap please login");
    		GoToField("#item_box");
		return;
	}
	if(item_ == ''){
		alert("Enter an Item barcode");
    		GoToField("#item_box");
		return;
	}
	var dhxWins,w1,	tabbar;
	dhxWins = new dhtmlXWindows();
    	dhxWins.enableAutoViewport(true);
	dhxWins.setImagePath("imgs/");
	w1 = dhxWins.createWindow("w1", 100, 100, 650,300);
	global_window = w1;
	dhxWins.attachEvent("onClose", function(win){
var x = $("#item_box").val();
	  	
		m120();
			$("#item_box").val(x);
			GoLocate();
			GoToField("#item_box");
		return true; 

    	});
    	w1.setText("Enter record: m49718.xml");
	w1.setModal(true);
    	tabbar = w1.attachTabbar();
    	tabbar.setSkin("dhx_skyblue");
    	tabbar.setImagePath("imgs/");
    	tabbar.attachEvent("onXLE", function() { //row_id will be the first row
    		showLoading(false);
        	SetMouseKeys();
    		SetValidator();
    		MakeDisableOnNew();
    		GoToField("#message_");
	});
	tabbar.attachEvent("onXLS", function() {
        	showLoading(true);
    	});
    	tabbar.loadXML("m49718.xml");
}

function GoNotItemTrap(){
	var SQL = "update copies set copytrap_ = " + "''" + " where copies.barcode_ = " + "'" + $("#item_box").val() + "'";
	var result = UpdateRecord(SQL,"tab");
	if(isNaN(result)){
		alert(result);
		return;
	}
	$("#trap_").text('');

}
function GoNewItemTrap(){
	if($("#message_").val() != '' && $("#id_").val() == ''){
		var SQL = "insert into traps(trap_) values('" + $("#message_").val() + "')";
		var result = InsertRecord(SQL,"tab");
		if(!isNaN(result))
			$("#id_").val(result);
		var SQL = "update copies set copytrap_ = " + "'" +$("#message_").val() + "'" + " where copies.barcode_ = " + "'" + $("#item_box").val() + "'";
		var result = UpdateRecord(SQL,"tab");
		if(isNaN(result)){
			alert(result);
			GoToField("#message_");
			return;
		}
		$("#trap").css("color", "red"); 
		$("#trap_").text($("#message_").val());
		global_trap_message = $("#message_").val();
		global_window.setText("Record Saved");
	}
	else
		GoToField("#message_");
}

function HandleFine(cfine,mygrid,id){
	var dhxWins,w1;
	dhxWins = new dhtmlXWindows();
    dhxWins.enableAutoViewport(true);
	dhxWins.setImagePath("imgs/");
	w1 = dhxWins.createWindow("w1", 100, 100, 850,450);
	global_window = w1;
	dhxWins.attachEvent("onClose", function(win){
		if($("#done_").val() != 'Yes'){
			GoToField("#item_box");
			return true;
		}
		else{
			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,fine_ = 0 where barcode_ = '" + barcode + "'";
			var result = UpdateRecord(SQL,"item_box");
			if(isNaN(result)){
				alert("DoReturn:" + SQL + ":" + result);
			}
			else{
				mygrid.setRowTextStyle(id, "color: red; ");
				mygrid.cells(id,8).setValue(1);
				mygrid.cells(id,9).setValue(0);
				GoToField("#item_box");
				if(global_item_reserved == 'y')
					ReserveQueue(item);	
				DoloanLog($("#borrower_box").val(),global_borrower_surname + " " + global_borrower_forename,barcode,global_item_title,"SHE",SetDate(global_today),GetTime(),global_item_fine,global_borrower_category,global_item_category,global_item_class,global_borrower_dept,global_borrower_course,global_borrower_tutor,global_borrower_charge,global_item_short,global_item_site);
			}
			$("#item_box").val('');
			GoToField("#item_box");
      		return true;
		}
	});
	w1.setText("Handle Fines");
	w1.setModal(true);
	var str = loadHtml("item_box","holdfines.div");
	w1.attachHTMLString(str);
	$("#borrower_").val($("#borrower_box").val());
	$("#item_").val($("#item_box").val());
	$("#held_").val(global_borrower_fines);
	$("#current_").val(cfine);
	var owe = 	parseFloat(global_borrower_fines) + parseFloat(cfine);
	$("#tendered_").val(owe.toFixed(2));
	$("#owing_").val("0.00");
	$("#credit_").val(owe.toFixed(2));
	$("#change_").val("0.00");
	$('#credit_').bind('change', function(e) { 
		var newowe = owe - parseFloat($("#credit_").val());
		var newtend = parseFloat($("#credit_").val());
		$("#tendered_").val(newtend.toFixed(2));
		$("#owing_").val(newowe.toFixed(2));
		$("#change_").val("0.00");
	});

	$('#tendered_').bind('change', function(e) { 
		var newchange = parseFloat($("#tendered_").val()) - parseFloat($("#credit_").val());;
		$("#change_").val(newchange.toFixed(2));
	});
	GoToField("#credit_");
	MakeDisable();
}
function HandleHeldFine(cfine){
	if(global_borrower_fines == '' || global_borrower_fines == "0.00"){
		alert("This borrower has no held fines");
		return;
	}	
	if(CheckMyPriv('manage:x.c.x.x') == false){
		$("#messages").text("No privilege for holding fines please login");
		GoToField("#item_box");
	return;
	}

	var dhxWins,w1;
	dhxWins = new dhtmlXWindows();
    dhxWins.enableAutoViewport(true);
	dhxWins.setImagePath("imgs/");
	w1 = dhxWins.createWindow("w1", 100, 100, 850,400);
	global_window = w1;
	dhxWins.attachEvent("onClose", function(win){
     		GoToField("#item_box");
      		return true; 
    });
	w1.setText("Handle Held Fines");
	w1.setModal(true);
	var str = loadHtml("item_box","heldfines.div");
	w1.attachHTMLString(str);
	$("#borrower_").val($("#borrower_box").val());
	$("#held_").val(global_borrower_fines);
	$("#tendered_").val(global_borrower_fines);
	$("#owing_").val("0.00");
	$("#credit_").val(global_borrower_fines);
	$("#change_").val("0.00");
	$('#credit_').bind('change', function(e) { 
		var newowe = parseFloat($("#held_").val()) - parseFloat($("#credit_").val());
		var newtend = parseFloat($("#credit_").val());
		$("#tendered_").val(newtend.toFixed(2));
		$("#owing_").val(newowe.toFixed(2));
		$("#change_").val("0.00");
	});

	$('#tendered_').bind('change', function(e) { 
		var newchange = parseFloat($("#tendered_").val()) - parseFloat($("#credit_").val());;
		$("#change_").val(newchange.toFixed(2));
	});
	GoToField("#credit_");
	MakeDisable();
}

function GoHoldFines(){
	if($("#done_").val() == "Yes"){
		return;
	}
	$("#tendered_").val("0.00");
	$("#credit_").val("0.00");
	$("#change_").val("0.00");
	var newowe = 	parseFloat(global_borrower_fines) + parseFloat(	$("#current_").val());
	$("#owing_").val(newowe.toFixed(2));
	var borrower = $("#borrower_").val();
	var item = $("#item_").val();
	var fine = 	$("#owing_").val();
	var SQL = "update members set fines_ = " + "'" + fine + "'" + " where barcode_ = " + "'" + borrower + "'";
	var result = UpdateRecord(SQL,"item_box");
	if(isNaN(result)){
		alert(result);
		return(false);
	}
	global_borrower_fines = fine;
	global_window.setText("Record Saved");
	$("#done_").val("Yes");
}

function GoPayFines(){
	if($("#done_").val() == "Yes"){
		return;
	}
	var borrower = $("#borrower_").val();
	var item = $("#item_").val();
	var fine = 	$("#owing_").val();
	var credit = $("#credit_").val();
	var SQL = "update members set fines_ = " + "'" + fine + "'" + " where barcode_ = " + "'" + borrower + "'";
	var result = UpdateRecord(SQL,"item_box");
	if(isNaN(result)){
		alert(result);
		return(false);
	}
	DofineLog($("#borrower_box").val(),global_borrower_surname + " " + global_borrower_forename,item,global_item_title,"CRE",SetDate(global_today),GetTime(),credit);
	global_borrower_fines = fine;
	global_window.setText("Record Saved");
	$("#done_").val("Yes");
}

function GoOffFines(){
	if($("#done_").val() == "Yes"){
		return;
	}
	var fine = $("#current_").val();
	$("#tendered_").val("0.00");
	$("#credit_").val("0.00");
	$("#change_").val("0.00");
	$("#owing_").val("0.00");
	var item = $("#item_").val();
	DofineLog($("#borrower_box").val(),global_borrower_surname + " " + global_borrower_forename,item,global_item_title,"OFF",SetDate(global_today),GetTime(),fine);
	global_borrower_fines = 0;
	global_window.setText("Record Saved");
	$("#done_").val("Yes");
}


function GoPayHeldFines(){
	if($("#done_").val() == "Yes"){
		return;
	}
	var borrower = $("#borrower_").val();
	var fine = 	$("#owing_").val();
	var credit = $("#credit_").val();
	var SQL = "update members set fines_ = " + "'" + fine + "'" + " where barcode_ = " + "'" + borrower + "'";
	var result = UpdateRecord(SQL,"item_box");
	if(isNaN(result)){
		alert(result);
		return(false);
	}
	DofineLog($("#borrower_box").val(),global_borrower_surname + " " + global_borrower_forename,'','',"CRE",SetDate(global_today),GetTime(),credit);
	global_borrower_fines = fine;
	global_window.setText("Record Saved");
	$("#done_").val("Yes");
}

function GoPrintHeldFines(){
	var borrower = $("#borrower_").val();
	var x = $("#sindex_").val().split(' ');
	var name = x[0] + " " + x[1];
	var held = $("#held_").val();
	var tendered = $("#tendered_").val();
	var owing = $("#owing_").val();
	var credit = $("#credit_").val();
	var change = $("#change_").val();
	var done = $("#done_").val();
	global_window.close();
	 var ihtml = $.ajax({
			method: "get",url: "heldfines_print.div", 
			async: false,
			beforeSend: function(){
				$("#tab").html('<img src="images/wait.gif" />');
				$("#tab").show("fast");
			},
			complete: function(){ 
				$("#tab").html('');
				$("#tab").hide("slow");
			}
		});
	 var str = ihtml.responseText;
	 str =str.replace('$borrower_p',borrower);
	 str =str.replace('$name_p',name);
	 str =str.replace('$held_p',held);
	 str =str.replace('$tendered_p',tendered);
	 str =str.replace('$owing_p',owing);
	 str =str.replace('$credit_p',credit);
	 str =str.replace('$change_p',change);
	 str =str.replace('$done_p',done);
	 
	var display_setting="toolbar=yes,location=no,directories=yes,menubar=yes,";
	display_setting+="scrollbars=no,width=600, height=300, left=100, top=25";

//	var content_innerhtml = document.getElementById("heldfinesform").innerHTML;
//	var content_innerhtml = document.getElementById("heldfinesform").innerHTML;
	var document_print=window.open("","",display_setting);
	document_print.document.open();
	document_print.document.write('<html><head><title>Print held fines </title></head>');
	document_print.document.write('<body>');
	document_print.document.write(str);
	document_print.document.write('</body></html>');
	$("#borrower_p").text(borrower);
	document_print.print();
	document_print.document.close();
	return false;
}

function GoOffHeldFines(){
	if($("#done_").val() == "Yes"){
		return;
	}
	$("#tendered_").val("0.00");
	$("#credit_").val("0.00");
	$("#change_").val("0.00");
	$("#owing_").val("0.00");
	DofineLog($("#borrower_box").val(),global_borrower_surname + " " + global_borrower_forename,'','',"OFF",SetDate(global_today),GetTime(),global_borrower_fines);
	global_borrower_fines = 0;
	global_window.setText("Record Saved");
	$("#done_").val("Yes");
}

function GoPayHistory(){
	var borrower_ = $("#borrower_box").val();
	if(borrower_ == ''){
		alert("Enter a borrower id");
    		GoToField("#borrower_box");
		return;
	}
	var dhxWins,w1,	tabbar;
	dhxWins = new dhtmlXWindows();
    	dhxWins.enableAutoViewport(true);
    	dhxWins.setImagePath("imgs/");
    	w1 = dhxWins.createWindow("w1", 100, 100, 800,400);
 	w1.setText("Borrower Payments History: " + borrower_);
 //	global_window = w1;
	w1.setModal(false);
	myhistorygrid = w1.attachGrid();
	var SQL = "select borrower_,name_,barcode_,title_,transact_,tdate_,ttime_,fine_ from fines where " + 	"borrower_ = '" + borrower_ + "'";
	var SQLCOLS = "borrower_,name_,barcode_,title_,transact_,tdate_,ttime_,fine_";
	
	myhistorygrid.setHeader("Borrower,Name,Barcode,Title,Transaction,Date,Time,Fine"); 
	myhistorygrid.setInitWidths("70,90,70,215,90,70,70,70"); 
	myhistorygrid.setColTypes("ro,ro,ro,ro,ro,ro,ro,ro");
	myhistorygrid.setColAlign("left,left,left,left,left,left,left,left"); 
	myhistorygrid.setColSorting("connector,connector,connector,connector,connector,connector,connector,connector");
	myhistorygrid.attachEvent("onXLE", function() {
		showLoading(false);
	});
   	myhistorygrid.attachEvent("onXLS", function() {
        	showLoading(true);
    	});
	dhxWins.attachEvent("onClose", function(win){
		return true; 
    	});
 	myhistorygrid.setImagePath("imgs/");
 	myhistorygrid.setSkin("light"); 
	myhistorygrid.init();
	myhistorygrid.enableColumnAutoSize(true);
	myhistorygrid.loadXML("connector.php?cmd="+SQL+"&cols="+SQLCOLS+"&");

}

function GoBorrowerCategory(line){
	var dhxWins,w1;
	dhxWins = new dhtmlXWindows();
    dhxWins.enableAutoViewport(true);
    dhxWins.setImagePath("imgs/");
    w1 = dhxWins.createWindow("w1", 100, 100, 800,400);
 	w1.setText("Borrower categories: ");
//	global_window = w1;
	w1.setModal(false);
	//	global_borrower_category
	var h = new Array();
	var f = new Array();
	var l = new Array();
	var a = new Array();
	var SQL;
	var SQLCOLS;
	var mygridc;
	mygridc = w1.attachGrid();
    ParseForm("m4952.xml",h,f,l,a);
    GridShow(mygridc,h,f,l,a,999,false); 
    SQL = "select " + f + " from borrower_category";
    SQLCOLS = f;
	var ESQL = escape(SQL);
	mygridc.attachEvent("onXLE", function() {
		showLoading(false);
	});
    mygridc.attachEvent("onXLS", function() {
        showLoading(true);
    });
 	mygridc.setImagePath("imgs/");
 	mygridc.setSkin("light"); 
	mygridc.init();
	mygridc.enableColumnAutoSize(true);
	mygridc.loadXML("connector.php?cmd="+ESQL+"&cols="+SQLCOLS+"&");
	mygridc.enableColumnAutoSize(false);
}
function GoStockCategory(line){
	var dhxWins,w1;
	dhxWins = new dhtmlXWindows();
    dhxWins.enableAutoViewport(true);
    dhxWins.setImagePath("imgs/");
    w1 = dhxWins.createWindow("w1", 100, 100, 800,400);
 	w1.setText("Stock categories: ");
//	global_window = w1;
	w1.setModal(false);
	//	global_borrower_category
	var h = new Array();
	var f = new Array();
	var l = new Array();
	var a = new Array();
	var SQL;
	var SQLCOLS;
	var mygridc;
	mygridc = w1.attachGrid();
    ParseForm("m4951.xml",h,f,l,a);
    GridShow(mygridc,h,f,l,a,999,false); 
    SQL = "select " + f + " from item_category";
    SQLCOLS = f;
	var ESQL = escape(SQL);
	mygridc.attachEvent("onXLE", function() {
		showLoading(false);
	});
    mygridc.attachEvent("onXLS", function() {
        showLoading(true);
    });
 	mygridc.setImagePath("imgs/");
 	mygridc.setSkin("light"); 
	mygridc.init();
	mygridc.enableColumnAutoSize(true);
	mygridc.loadXML("connector.php?cmd="+ESQL+"&cols="+SQLCOLS+"&");
	mygridc.enableColumnAutoSize(false);
}
function GoBorrowerRecord(){
	var borrower_ = $("#borrower_box").val();
	if(borrower_ == ''){
		alert("Enter a borrower id");
    		GoToField("#borrower_box");
		return;
	}

	var dhxWins,w1,	tabbar;
	dhxWins = new dhtmlXWindows();
    dhxWins.enableAutoViewport(true);
    dhxWins.setImagePath("imgs/");
    w1 = dhxWins.createWindow("w1", 100, 100, 750, 600);
    w1.setText("Borrower record");
	global_window = w1;
	w1.setModal(true);
	dhxWins.attachEvent("onClose", function(win){
		var x = $("#borrower_box").val();
  	
	m120();
		$("#borrower_box").val(x);
		GoLocate();
		GoToField("#borrower_box");
	return true; 
	});
    tabbar = w1.attachTabbar();
    tabbar.setSkin("dhx_skyblue");
    tabbar.setImagePath("imgs/");
    tabbar.attachEvent("onXLE", function() { //row_id will be the first row
        showLoading(false);
    	var result = new Array();
    	var h = new Array();
    	var f = new Array();
    	var l = new Array();
    	var a = new Array();
    	var SQLCOLS;
        ParseForm("m211.xml",h,f,l,a);
    	SQLCOLS = f.join(",");
    	var SQL = "select " + f +  " from members where barcode_ = " + 	$("#borrower_box").val();
    	AjaxSql("borrower_box",SQL,SQLCOLS,result);
    	var cnt = result[0];
    	if(cnt == 0){
    		alert("No records Found");
    		return;
    	}
    	for(var j=0;j<f.length;j++){
    		var x = result[j+1];
    		$("#" + f[j]).val(x);
    	}
     	SetMouseKeys();
    	SetValidator();
    	MakeDisable();
    	MakeDates();
    	GoToField("#title_");
	});
    tabbar.attachEvent("onXLS", function() {
        showLoading(true);
    });
    tabbar.loadXML("m211.xml");
} 
function GoStockRecord(){
	var item_ = $("#item_box").val();
	if(item_ == ''){
		alert("Enter an item id");
    		GoToField("#item_box");
		return;
	}

	StockRecord();
	
}
function StockRecord(){
	var dhxWins, w1, tabbar;
	dhxWins = new dhtmlXWindows();
	dhxWins.enableAutoViewport(true);
	dhxWins.setImagePath("imgs/");
	w1 = dhxWins.createWindow("w1", 20, 30, 750, 500);
	global_window = w1;
	w1.setText("Amend Catalogue Record: m1101cm2");
	w1.denyMove();
	w1.denyResize();
	w1.clearIcon();
	w1.denyPark();
	w1.setModal(true);
	dhxWins.attachEvent("onClose", function(win){
		var x = $("#item_box").val();
  	
	m120();
		$("#item_box").val(x);
		GoLocate();
		GoToField("#item_box");
	return true; 
	});
	tabbar = w1.attachTabbar("top");
	tabbar.setSkin("dhx_skyblue");
	tabbar.setImagePath("imgs/");
	tabbar.loadXML("m1102.xml");
	tabbar.attachEvent("onXLE", function() { //row_id will be the first row
		showLoading(false);
		var result = new Array();
		var h = new Array();
		var f = new Array();
		var l = new Array();
		var a = new Array();
		var SQLCOLS;
	    ParseForm("m1102.xml",h,f,l,a);
		SQLCOLS = f.join(",");	
		var SQL = "select catalogue.* from catalogue,copies where catalogue.id_ = copies.catalogue_ and copies.barcode_ = " + 	$("#item_box").val();
		AjaxSql("item_box",SQL,SQLCOLS,result);
		var cnt = result[0];
		if(cnt == 0){
			alert("No records Found");
			return;
		}
		for(var j=0;j<f.length;j++){
			var x = result[j+1];
			$("#" + f[j]).val(x);
		}
	 	SetMouseKeys();
	 	SetValidator();
	 	MakeDisable();
	 	MakeDates();
		GoToField("#isbn_");
	 });
	 tabbar.attachEvent("onXLS", function() {
	    showLoading(true);
	 });
} 

function GoBarcodeRecord(){
	var item_ = $("#item_box").val();
	if(item_ == ''){
		alert("Enter an item id");
    		GoToField("#item_box");
		return;
	}

	BarcodeRecord();
	
}
function BarcodeRecord(){
	var dhxWins, w1, tabbar;
	dhxWins = new dhtmlXWindows();
	dhxWins.enableAutoViewport(true);
	dhxWins.setImagePath("imgs/");
	w1 = dhxWins.createWindow("w1", 20, 30, 650, 600);
	global_window = w1;
	w1.setText("Amend Copy Record: m1103cm1");
	w1.denyMove();
	w1.denyResize();
	w1.clearIcon();
	w1.denyPark();
	w1.setModal(true);
	dhxWins.attachEvent("onClose", function(win){
		var x = $("#item_box").val();
  	
	m120();
		$("#item_box").val(x);
		GoLocate();
		GoToField("#item_box");
	return true; 
	});
	tabbar = w1.attachTabbar("top");
	tabbar.setSkin("dhx_skyblue");
	tabbar.setImagePath("imgs/");
	tabbar.loadXML("m1103.xml");
	tabbar.attachEvent("onXLE", function() { //row_id will be the first row
		showLoading(false);
		var result = new Array();
		var h = new Array();
		var f = new Array();
		var l = new Array();
		var a = new Array();
		var SQLCOLS;
	    ParseForm("m1103.xml",h,f,l,a);
		SQLCOLS = f.join(",");	
		var SQL = "select * from copies where barcode_ =  " + 	$("#item_box").val();

		AjaxSql("item_box",SQL,SQLCOLS,result);

		var cnt = result[0];
		if(cnt == 0){
			alert("No records Found");
			return;
		}
		for(var j=0;j<f.length;j++){
			var x = result[j+1];
			$("#" + f[j]).val(x);
		}
	 	SetMouseKeys();
	 	SetValidator();
	 	MakeDisable();
	 	MakeDates();
		GoToField("#category_");
	 });
	 tabbar.attachEvent("onXLS", function() {
	    showLoading(true);
	 });
} 

function InitArray(A) {
	var len = A.length;
	A.length = 0;
	for ( var i = 0; i < len; i++) {
		A.pop();
	}
	A = [];
}

