var selectResult;
var photoDisplay = "<table><tr><td><img src='http://www.facefax.net/images/woman.jpg' height='240' width='240' /></td><td><img src='http://www.facefax.net/images/man.jpg'  height='240' width='240'/></td></tr></table>";
var emptyString = /^\s*$/
var global_admin = 'xsoft@btconnect.com';
var global_developer = 'xsoft@btconnect.com';
var global_xmlLog;
var glb_vfld;      // retain vfld for timer thread
var grid_overdues;
var grid_onloan;
var grid_run;
var grid_issues;
var grid_orders;
var grid_quick;
var checkThese = new Array("library","address","contact","email","login","password");
var checkTheseName = new Array("Library","Address","Contact","Email","Login","Password");
var saveThese = new Array("library","address","contact","telephone","email","code","login","password");
var SQL_ONLOAN = "select borrower_,surname_,forename_,barcode_,title_,DATE_FORMAT(return_,'%d/%m/%Y') as return_,price_  from catalogue  where status_ = 'LOA' order by borrower_";  
var SQL_ONLOAN_COLS = "borrower_,surname_,forename_,barcode_,title_,return_,price_";
var SQL_COPYFROM = "select isbn_,class_,authors_,editors_,title_,edition_,pubyear_,pubcountry_,subjects_,publisher_,media_,description_,series_,price_,keywords_,synopsis_,order_,notes_,category_,site_,ceiling_,finedelay_,shelf_ from catalogue,copies where catalogue.id_ = copies.catalogue_ and $param = '$param_value'";


 function MyRegister(){
	 var ihtml = $.ajax({
			method: "get",url: "register.div", 
			async: false,
			beforeSend: function(){
				$("#tab").html('<img src="/images/wait.gif" />');
				$("#tab").show("fast");
			},
			complete: function(){ 
				$("#tab").html('');
				$("#tab").hide("slow");
			}
		});	
		var selectResult = "<div style=\"background: white; width:650px;height:270px;padding:10px; margin:0px\">" +
		ihtml.responseText + "</div>";
		Tip(
		selectResult,CLICKSTICKY, true, CLICKCLOSE, false, 
		CLOSEBTN, true,SHADOW, true,	
		TITLE, 'Make contact', PADDING, 9,FIX, ['Make contact', 0, 5],
		WIDTH,650,FONTFACE, 'Arial, Helvetica, sans-serif', FONTSIZE, '10pt',TITLEALIGN, 'center');
		$(document).ready(function(){
			SetValidator(20);
			GoToField("#library_");
		});
 }
 
 function GoRegister(){
//email to enquirer
	var v = $("#cmaForm").validate();
	if(!v.form())
		return;
	var send_to = $("#email_").val;
	var bcc_to = "";
	var subject = "Cyberlibrary enquiry";
	var message = "Thank for your enquiry about Cyberlibrary. We will be in touch shortly by email with more information";
	$.ajax({
		type: "post",url: "phpmailer.php", data:"send_to=" + send_to + "&bcc_to=" + bcc_to + "&subject=" + subject + "&message=" + message, 
	    async: false,
	    beforeSend: function(){
		  $("#tab").html('<img src="/images/wait.gif" />');
		  $("#tab").show("fast");
		},
		complete: function(){ 
			$("#tab").html('');
			$("#tab").hide("slow");
		}
	});
//email to me
	var SQL = "insert into demo(library_,address_,contact_,telephone_,email_) values ('" +
	$("#library_").val() + "','" +
	$("#address_").val() + "','" +
	$("#contact_").val() + "','" +
	$("#telephone_").val() + "','" +
	$("#email_").val() + "')";
	var send_to = "xsoft@btconnect.com";
	var bcc_to = "";
	var subject = "Cyberlibrary enquiry";
	var message = "Enquiry from " + 
	$("#library_").val() + "<br/>" +
	$("#address_").val() + "<br/>" +
	$("#contact_").val() + "<br/>" +
	$("#telephone_").val() + "<br/>" +
	"<a href=mailto:" + $("#email_").val()+ ">" + $("#email_").val() + "</a>";
	$.ajax({
		type: "post",url: "phpmailer.php", data:"send_to=" + send_to + "&bcc_to=" + bcc_to + "&subject=" + subject + "&message=" + message, 
	    async: false,
	    beforeSend: function(){
		  $("#tab").html('<img src="/images/wait.gif" />');
		  $("#tab").show("fast");
		},
		complete: function(){ 
			$("#tab").html('');
			$("#tab").hide("slow");
		}
	});
//record in database

	var mainresult = InsertRecord(SQL,"tab");
	if(isNaN(mainresult)){
		var message = "Enquiry insert error " + mainresult;
		$.ajax({
			type: "post",url: "phpmailer.php", data:"send_to=" + send_to + "&bcc_to=" + bcc_to + "&subject=" + subject + "&message=" + message, 
		    async: false,
		    beforeSend: function(){
			  $("#tab").html('<img src="/images/wait.gif" />');
			  $("#tab").show("fast");
			},
			complete: function(){ 
				$("#tab").html('');
				$("#tab").hide("slow");
			}
		});
	}
	var selectResult = "<div style=\"background: white; width:350px;height:100px;padding-top:5px;text-align:center;\">" +
	"Thanks for your enquiry we will be in touch by email" + "</div>";
	Tip(
	selectResult,CLICKSTICKY, true, CLICKCLOSE, false, 
	CLOSEBTN, true,SHADOW, true,	
	TITLE, 'Enquiry received', PADDING, 9,FIX, ['Make contact', 0, 5],
	WIDTH,350,FONTFACE, 'Arial, Helvetica, sans-serif', FONTSIZE, '10pt',TITLEALIGN, 'center');
	$("#tab").html('');
	$("#tab").hide("slow");
}
 
function MyLogin(){
	 var ihtml = $.ajax({
			method: "get",url: "login.div", 
			async: false,
			beforeSend: function(){
				$("#tab").html('<img src="/images/wait.gif" />');
				$("#tab").show("fast");
			},
			complete: function(){ 
				$("#tab").html('');
				$("#tab").hide("slow");
			}
		});	
		var selectResult = "<div style=\"background: white; width:450px;height:120px;padding:10px; margin:0px\">" +
		ihtml.responseText + "</div>";
		Tip(
		selectResult,CLICKSTICKY, true, CLICKCLOSE, false, 
		CLOSEBTN, true,SHADOW, true,	
		TITLE, 'Login', PADDING, 9,FIX, ['Login', 0, 5],
		WIDTH,480,FONTFACE, 'Arial, Helvetica, sans-serif', FONTSIZE, '10pt',TITLEALIGN, 'center');
		$(document).ready(function(){
			SetValidator(20);
			GoToField("#login_");
		});
//send email
		var send_to = "xsoft@btconnect.com"
		var bcc_to = "";
		var subject = "Cyberlibrary login";
		var message = "Someome has attempted a login";
		$.ajax({
			type: "post",url: "phpmailer.php", data:"send_to=" + send_to + "&bcc_to=" + bcc_to + "&subject=" + subject + "&message=" + message, 
		    async: false,
		    beforeSend: function(){
			  $("#tab").html('<img src="/images/wait.gif" />');
			  $("#tab").show("fast");
			},
			complete: function(){ 
				$("#tab").html('');
				$("#tab").hide("slow");
			}
		});
 }
 
 function GoLogin(){
//email to me
	var v = $("#cmaForm").validate();
	if(!v.form())
		return;
	var send_to = "xsoft@btconnect.com";
	var bcc_to = "";
	var subject = "Cyberlibrary login";
	var message = "Login " + $("#login_").val();
	$.ajax({
		type: "post",url: "phpmailer.php", data:"send_to=" + send_to + " bcc_to=" + bcc_to + " subject=" + subject + " message=" + message, 
	    async: false,
	    beforeSend: function(){
		  $("#tab").html('<img src="/images/wait.gif" />');
		  $("#tab").show("fast");
		},
		complete: function(){ 
			$("#tab").hide("fast");
		}
	});
//check access
	var SQL = "select name_,privileges_ from users where login_ =" + "'" + $("#login_").val() + "'" + " and password_ =" + "'" + $("#password_").val(); + "'"; 
	var SQLCOLS = "name_,privileges_";  
	var result = new Array();
	var ret;
	AjaxSql("tab",SQL,SQLCOLS,result);
	if(result[0] != 1){
		alert("Unknown User");
		ret = "notok";
	}
	else{
		alert("Welcome back " + result[1]);
		ret = "ok";
	}
//record in database
	var SQL = "insert into logins(type_,login_,password_,result_) +" +
			" values('" +
			"login" + "','" +
			$("#login_").val() + "','" +
			$("#password_").val() + "','" +
			ret + "','" 
			;
	var mainresult = InsertRecord(SQL,"tab");
	if(isNaN(mainresult)){
		var message = "Login insert error " + mainresult;
		$.ajax({
			type: "post",url: "phpmailer.php", data:"send_to=" + send_to + " bcc_to=" + bcc_to + " subject=" + subject + " message=" + message, 
		    async: false,
		    beforeSend: function(){
			  $("#tab").html('<img src="/images/wait.gif" />');
			  $("#tab").show("fast");
			},
			complete: function(){ 
				$("#tab").hide("fast");
			}
		});
	}
}
 function MyProblem(){
	 var ihtml = $.ajax({
			method: "get",url: "problem.div", 
			async: false,
			beforeSend: function(){
				$("#tab").html('<img src="/images/wait.gif" />');
				$("#tab").show("fast");
			},
			complete: function(){ 
				$("#tab").html('');
				$("#tab").hide("slow");
			}
		});	
		var selectResult = "<div style=\"background: white; width:650px;height:230px;padding:10px; margin:0px\">" +
		ihtml.responseText + "</div>";
		Tip(
		selectResult,CLICKSTICKY, true, CLICKCLOSE, false, 
		CLOSEBTN, true,SHADOW, true,	
		TITLE, 'Problem', PADDING, 9,FIX, ['Problem', 0, 5],
		WIDTH,680,FONTFACE, 'Arial, Helvetica, sans-serif', FONTSIZE, '10pt',TITLEALIGN, 'center');
		$(document).ready(function(){
			SetValidator(20);
			GoToField("#library_");
		});
 }
 
 function GoProblem(){
//email to me
	var v = $("#cmaForm").validate();
	if(!v.form())
		return;
	var send_to = "xsoft@btconnect.com";
	var bcc_to = "";
	var subject = "Cyberlibrary problem";
	var message = "Problem " + $("#problem_").val() + " " +  $("#library_").val() + " " +  $("#email_").val();
	$.ajax({
		type: "post",url: "phpmailer.php", data:"send_to=" + send_to + " bcc_to=" + bcc_to + " subject=" + subject + " message=" + message, 
	    async: false,
	    beforeSend: function(){
		  $("#tab").html('<img src="/images/wait.gif" />');
		  $("#tab").show("fast");
		},
		complete: function(){ 
			$("#tab").hide("fast");
		}
	});
}

function xmlencode(string) {
    return string.replace(/\&/g,'&'+'amp;').replace(/</g,'&'+'lt;')
        .replace(/>/g,'&'+'gt;').replace(/\'/g,'&'+'apos;').replace(/\"/g,'&'+'quot;');
}


//mygrid.groupBy(2);
function GoAuthority(fieldname,header,phpfile,seed,popit,multi,finder,pick){
	var copyfrom = '';
	if(finder != '')
		copyfrom = $("#" + finder).val();
	var myValue = $(popit).val();
	var ihtml=	"<div>Please choose the correct term</div>" +
	"	<div id=\"combo\" style=\"width:200px; height:15px;\"></div>";
	var result = false;
	if(finder != '' && myValue != '' && findmode == false){		//see if there is a valid entry already in the box
		result = Populate("gophptable.php",copyfrom,fieldname,myValue);
	}
	if(result == false){
		if(myValue == '')
			myValue = seed;
		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(myValue);
		z.setOptionHeight(300);
		z.attachEvent("onChange", function(value,state){Pop(z,popit,multi,copyfrom,fieldname,pick);});
	}
}


function Populate(php,copyfrom,fieldname,myValue)
{
	var result = false;
	myValue = myValue.replace(/'/g,"\\'");
	myValue = myValue.replace(/"/g,"\"");
	var SQL = copyfrom.replace('$param',fieldname);
	SQL = SQL.replace('$param_value',myValue);
	var COLS = copyfrom.replace('select ','');
	var pos1=COLS.indexOf('from');
	var str = COLS.substring(0,pos1);
	str = str.replace(/ /g,"");
	var COLS_ARRAY = str.split(',');
	$.ajax({
	   	method: "get",url: 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;
	   		$(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 = '';
	        		myData = myData.replace(/:/g,":\n");
	        		if(COLS_ARRAY[j] == "catalogued_" || COLS_ARRAY[j] == "startsub_" || COLS_ARRAY[j] == "renew_" ){
	        			$("#" + COLS_ARRAY[j]).val(GetDate(myData));
	        		}
	        		else
	        			$("#" + COLS_ARRAY[j]).val(myData);
	        	}
	   			result = true;
	   		});
	   	}
	});
	return(result);
}

function Pop(z,MyBox,Multi,copyfrom,fieldname,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];
	}
	var oldtext = $(MyBox).val();
	if(Multi && oldtext != '')
		$(MyBox).val(oldtext + ":\n" + myValue);
	else
		$(MyBox).val(myValue);
//	if(copyfrom != '' && findmode == false)
//		Populate("gophptable.php",copyfrom,fieldname,myValue);
	UnTip();

}

function GoBarcode(){
	var myValue = $("#barcode_").val();
	if(myValue != ''){
		var copyfrom = $("#copyfrom").val(); 
		Populate("gophptable.php",copyfrom,"barcode_",myValue);
	}
}