function addrec(totable) {  // also addrec_evt ... actions on success differ
				//NOTE not really generic if it calls ajq_saveart,
				// however, in ajq_saveart the tablename is used to hardcode certain initial fields and xlate some stuff, like dates
    		$.ajax({
   			type: "POST",
   			url: "ajq_saveart.php",
			data: "tablename="+totable ,  //with no record_id creates new record
			dataType: "json",
   			success: function(jr){
   				logthis("new rec no="+jr.respz.newid)
   				fetcharticlefor(jr.respz.newid)
   			}
 		});
}

function addrec_ads(totable) {  // also addrec_evt ... actions on success differ
				//NOTE not really generic if it calls ajq_saveart,
				// however, in ajq_saveart the tablename is used to hardcode certain initial fields and xlate some stuff, like dates
    		$.ajax({
   			type: "POST",
   			url: "ajq_saveart.php",
			data: "tablename="+totable ,  //with no record_id creates new record
			dataType: "json",
   			success: function(jr){
   				logthis("new rec no="+jr.respz.newid)
				if ((totable=="ads") || (totable=="announce")) window.location.reload()
				else window.location=totable+'.php?id='+jr.respz.newid
   				//fetcharticlefor(jr.respz.newid)
   			}
 		});
}

function addrec_issues(totable) {  // also addrec_evt ... actions on success differ
				//NOTE not really generic if it calls ajq_saveart,
				// however, in ajq_saveart the tablename is used to hardcode certain initial fields and xlate some stuff, like dates
    		$.ajax({
   			type: "POST",
   			url: "ajq_saveart.php",
			data: "tablename="+totable ,  //with no record_id creates new record
			dataType: "json",
   			success: function(jr){
   				logthis("new rec no="+jr.respz.newid)
				if ((totable=="ads") || (totable=="announce")) window.location.reload()
				else window.location=totable+'.php?id='+jr.respz.newid
   			}
 		});
}

function addrec_art(totable) {  // also addrec_evt ... actions on success differ

    	$.ajax({
   			type: "POST",
   			url: "ajq_saveart.php",
			data: "tablename="+totable+"&content="+ $('#addrec_art').attr('content'),  //with no record_id creates new record
			dataType: "json",
   			success: function(jr){
   				logthis("new rec no="+jr.respz.newid)
   				fetcharticlefor(jr.respz.newid)
   			}
 		});
}

function addrec_rvw(totable) {  // also addrec_evt ... actions on success differ
    		$.ajax({
   			type: "POST",
   			url: "ajq_saveart.php",
			data: "tablename="+totable+"&content="+$('#addrec_rvw').attr('content') ,  //with no record_id creates new record
			dataType: "json",
   			success: function(jr){
   				logthis("new rec no="+jr.respz.newid)
				$('#commentcontainer').remove()
//   				DoenAjax_fetchrvwdetail(jr.respz.newid)
				DoenAjax_fetchrvwdetail_indiv(jr.respz.newid,"centreblock")
				$('#centreblock').fadeIn('slow')
   			}
 		});
}

function DoenAjax_buildinput_for(table,tableidfield,targetdiv,recno) {
	// NOTE: recno contains area_id in case of form for new listings
	// however, empty listings should be dealt with by DoenAjax_buildinput_form (note "_m_")
	//calls wrap... to setup containing controls
	// this creates a formlike control where each field is updated as it changes
	var poststr="table="+table+"&tableidfield="+tableidfield+"&recno="+recno+"&targetdiv="+targetdiv
//	logthis('<span class="removable">'+poststr+'</span>')

		$.ajax({
   			type: "POST",
   			url: "ajq_buildinput.php",
			data: poststr,
			dataType: "json",
   			success: function(jr){
   				$('#picuplctrl').remove()
				$('#'+jr.respz.targetdiv)
				.html(jr.respz.html)
				.find(".ajxupd").each( function() { // individual inputs update via ajax
					$(this).change(function() {
						var field=$(this).attr('field')
						var ctrlid=$(this).attr('ctrlid')
						var table=$(this).attr('table')
						var keyfield=$(this).attr('keyfield')
						var keyvalue=$(this).attr('keyvalue')
						DoenAjax_updatetable(field,ctrlid,table,field,keyfield,keyvalue);
//						logthis("upd:"+field+"/"+ctrlid+"/"+table+"/"+field+"/"+keyfield+"/"+keyvalue)
						//			(inputidprefix,inputid,table,field,tableidfield,tableidvalue)
							})
					});
				 DoenAjax_getrow_for(jr.respz.table,jr.respz.tableidfield,jr.respz.recno)
				 	//contents from dbase
				$('.calendarButton')
					.calendar({autoPopUp: 'button',
							buttonImageOnly: true,
							buttonImage: 'calendar.gif',
							buttonText: 'Calendar',
							minDate : new Date(2007, 1 - 1, 26),
							maxDate : new Date(2020, 1 - 1, 26),
							dateFormat : 'YMD-'
					})

   			}
 		});
}



function DoenAjax_buildinput_form(table,tableidfield,targetdiv) { //note "m" in for_m_
	//calls ajax wrap, but wraps all in form
	//  now recno will just be hardcoded to new
// 	($formid,$actionurl,$dblinkng,$fields,$table,
// 			 		$keyfield,$keyvalue,$ctrlid,$initvalue)

	var recno="new"

	var poststr="table="+table+"&tableidfield="+tableidfield+"&recno="+recno+"&targetdiv="+targetdiv+"&formid=newlistingform&actionurl=ajq_saveform.php"
		$.ajax({
   			type: "POST",
   			url: "ajq_buildinputform.php",
			data: poststr,
			dataType: "json",
   			success: function(jr){
				$('#'+jr.respz.targetdiv)
				.html(jr.respz.html+'<hr>'+jr.respz.picuploadform+'<hr>'/*+jr.respz.logstring*/)
				.find("#newlistingform")
				.submit(function(){
					submitbannerform(this,jr.respz.targetdiv)
					return false;
					})
			if (($.browser.msie) && (table=="banners")){
				$('.picuploadformclass').html('MSIE browser detected.  Please submit details before uploading an image')
			}
			else $(".picform").each(function() {
				 	prepareUploadform(this,$(this).attr('id'))
				 				})
				 	// still gotta figure out how to link uploaded pic to rest of record not created yet
				 	// try hardcoding for banners situation, has to be done in ajaxforms handling form submission
   			}
 		});
}

function validateform(formobj) {
	var s="Validating input.\n"
	var notok=0
	$(formobj).find("select").each(function(j) {
			var entry=$(this).val()
			var isreq=$(this).attr("rqurd")
			if (isreq=="yes") {
				if ( entry=="empty") {
					notok++;
					s+=notok+":"+$(this).attr('name')+"=>"+entry+"\n"
					$(this).addClass('failvalidate')
				}
				else $(this).removeClass('failvalidate')
			}
		})

	$(formobj).find("input").each(function(j) {
			var entry=$(this).val()
			var isreq=$(this).attr("rqurd")
			if (isreq=="yes") {
				if ( entry=="") {
					notok++;
					s+=notok+":"+$(this).attr('name')+"=>"+entry+"\n"
					$(this).addClass('failvalidate')
				}
				else $(this).removeClass('failvalidate')
			}
		})

	$(formobj).find("textarea").each(function(j) {
			var entry=$(this).val()
			var isreq=$(this).attr("rqurd")
			if (isreq=="yes") {
				if ( entry=="") {
					notok++;
					s+=notok+":"+$(this).attr('name')+"=>"+entry+"\n"
					$(this).addClass('failvalidate')
				}
				else $(this).removeClass('failvalidate')
			}
		})
	if (notok>0) alert('Please complete the fields shaded red')

	return notok
}


function submitbannerform(formobj,targetdiv) {
   // only new listings are submitted this way (post)
   // once submitted, the record is treated as existing, and is edited with per field ajax updates
   // to get this going, build an ajax-wrapped form and plug it into the targetdiv -- once ajax is successfull
   //NOTE: hardcoded table in next line
 	var poststr=$(formobj).formSerialize()+"&targetdiv="+targetdiv+"&table=banners"
 	//TODO does ajq_saveform.php need a table var?
 	if (validateform(formobj)==0) {  //counts no of erroneous fields
 		logthis('<span class="removable">Validated. Submitting</span>')

		$.ajax({
   			type: "POST",
   			url: "ajq_saveform.php",
			data: poststr,
			dataType: "json",
   			success: function(jr){
				$('#'+jr.respz.targetdiv)
				.html(jr.respz.html)
				DoenAjax_buildinput_for_plusbanners("banners","record_id",targetdiv,jr.respz.record_id)
				//					table 	idfield/keyfield	passed back from ajq_saveform
				// this will build an empty ajax-wrapped form,
				// and will chain onto calling contents from the table and plug these into the DOM
   			}
 		});
 	}
}


function DoenAjax_getrow_for(table,tableidfield,recno) { //gets recno from submitting control
	//needs containing controls to be setup
// 	var recno_in_form=document.getElementById("recno") //put the submitted value into form
//	recno_in_form.value=recno
	var poststr="table="+table+"&tableidfield="+tableidfield+"&recno="+recno
		$.ajax({
   			type: "POST",
   			url: "ajq_getrow.php",
			data: poststr,
			dataType: "json",
   			success: function(jr){
   				var teststring=""
   				var key
   				var sessionlevel=0
   				if (jr.respz.level) var sessionlevel=jr.respz.level
   				if ((sessionlevel=="admin") || (sessionlevel=="super")) sessionlevel=1
				if ((jr.tablerow.length==undefined) ||(jr.tablerow.length==0)) logthis('empty record'+"\n"+jr.tablerow.length)
				else {
				  for (key in jr.tablerow[0]) {
					var fid=key+jr.respz.recno
					var fval=jr.tablerow[0][key]
					teststring=teststring+fid+"="+fval+"\n"
					if (sessionlevel>0) $('#'+fid).val(fval) //val for editable, html for non-editable
					else 			$('#'+fid).html(fval)

					}

				  }//else
				}
 		});
 }


function DoenAjax_updatetable(inputidprefix,inputid,table,field,tableidfield,tableidvalue) {
/*	logthis('<span class="removable">'+inputidprefix+"&bull;"+inputid+'</span>')*/
//logthis("update:"+inputidprefix+"/"+inputid+"/"+table+"/"+field+"/"+tableidfield+"/"+tableidvalue)
//alert(inputidprefix+"\n"+inputid+"\n"+table+"\n"+field+"\n"+tableidfield+"\n"+tableidvalue)
// if error comes up :"userinput has no properties", ensure that php set the id to field.ctrlid
 	var userinput=document.getElementById(inputidprefix+inputid)
	var t_clean=userinput.value.replace(/\&/g, "(ampersand)")
	var  feedback=document.getElementById("feedback")
  	var poststr="inputidprefix="+inputidprefix+"&inputid="+inputid+"&table="+table+"&field="+field+"&newvalue="+t_clean+"&tableidfield="+tableidfield+"&tableidvalue="+tableidvalue
	userinput.style.color="red"
	userinput.value="Updating ..."
/*	logthis('<span class="removable">Updating ...'+poststr+'</span>')*/
		$.ajax({
   			type: "POST",
   			url: "ajq_updatetable.php",
			data: poststr,
			dataType: "json",
   			success: function(jr){
   				$('#'+jr.respz.targetid).val(jr.respz.newvalue).attr('style','color:blue')
				if (jr.respz.newid>0) {
					alert ("Added record: "+jr.respz.newid)
					$('#recid').val(jr.respz.newid) // TODO ?? shouldnt this be recid+local_id
					// added record should get a container with correct dom ids for controls
					DoenAjax_buildinput_for('users','title_id',"addedrec",jr.respz.newid)
					DoenAjax_getrow_for('users','title_id',r.respz.newid)
				}
			}
 		});


}

function addrec() {
//	var poststr="table="+table+"&tableidfield="+tableidfield+"&recno="+recno+"&targetdiv="+targetdiv
//		target=addedrec, container of New Record control
//						(table,tableidfield,targetdiv,recno)
	DoenAjax_buildinput_for('users','title_id',"addedrec",0);
	// this should build an empty record control block, when anything is saved, a record will be added
	// however, this will not update the dom control ids ...
	// therefore the returning content (json) from the php script should repaint this control

}
//==========================================
function DoenAjax_addpicuploadcontrol_recno(recno,targetdiv) {
	// with record_id, the rest can be looked up

//($record_id,$picfield,$pictable,$area_id,$listing_id)
// recno===record_id
  var poststr="recno="+recno+"&targetdiv="+targetdiv
		$.ajax({
   			type: "POST",
   			url: "ajq_buildpicuplctrl.php",
			data: poststr,
			dataType: "json",
   			success: function(jr){
   				$('#'+jr.respz.targetdiv).html('<div class="removable">'+jr.respz.html+'</div>')
				 $(".picform").each(function() {

					prepareUploadform(this,$(this).attr('id'))
					})
			}
 		});
}


//===================================
function prepareUploadform (formobject,formid) {
// if this doesnt work but the submit button actually reroutes to the action url ....? => elke form moet unieke id he, soos opgestel deur bv makepicuploadform() in dbfunct.php
// this .js file must be included in the html header -- obviously!
   if($.browser.msie) {
   	 $('#'+formid).find("input[@name='brwsr']").val("msie")
		var lostway='IE has lost its way :('+"\nStand by while the page is refreshed\nto see the changes.\nYou may click on the Redo or Refresh links if nothing happens\n"+"Or just get Firefox already"
   	 return
   }
	else {
  	$('#'+formid).find("input[@name='brwsr']").val("ff")
		var lostway ="Please refresh your browser manually\nYou may click on the Redo or Refresh links\nPlease inform the webmaster if this problem persists"
	}
//   	 return
     $('#'+formid)
        .ajaxForm({
/*            		beforeSubmit : function() {
            				alert('before submitting')},*/

		  success: function(resp) {

            			var picpath =resp.respz.picdestdir+"/"+resp.respz.picname

            				//picpos is also passed as resp.respz.destpicidprefix
							//$("#showpichere").html("<img src="+picpath+">")
							//from makepicuploadform
							//there are many reviews on a page, picholders go by picpos_+record_id
						if (resp.respz.pictable=='reviews') {
							$('#picpos_'+resp.respz.record_id).attr("src",picpath)
							logthis("cdvrwimage to\n"+'#picpos_'+resp.respz.record_id)
							$('#multi_picpos_'+resp.respz.record_id).attr("src",picpath)
							logthis("cdvrwimage to\n"+'#picpos_'+resp.respz.record_id)

						}
						else if  (resp.respz.pictable=="banners") {
							$("#showpichere").html("<img src="+picpath+">")
            				 //banners database functions:
            				 $("#pic1new").val(picpath)
            				 $("#pic1"+resp.respz.record_id).val(resp.respz.picname)
						}
						else {
							$('#'+resp.respz.destpicidprefix+resp.respz.picfield).attr("src",picpath)
						}

        					} ,
     		   dataType:  "json",
     		   error : function() {
     		     alert(lostway)
					$('#reread').click()

						}
         		});
}





function delete_art() {
	var recno=$('#deleterecord_art').attr("artno")
	if (confirm("Are you sure you want to \ndelete record no\n"+recno)) {
		var poststr="recno="+recno+"&tablename=articles&targetdiv=centreblock"
		 $.ajax({
   			type: "POST",
   			url: "ajq_deleterec.php",
			data: poststr,
			dataType: "json",
   			success: function(jr){
/*   				$('#'+jr.respz.targetdiv).html('<div class="removable">'+jr.respz.html+'</div>')
				 $(".picform").each(function() {prepareUploadform(this,$(this).attr('id'))})*/
				window.location="articles.php?articlescat=art"
			}
 		});
	}

}



function getmailfriendform(obj,xpos,ypos) {
	var poststr="record_id="+$(obj).attr('record_id')+"&category="+$(obj).attr('category')
		$.ajax({
   			type: "POST",
   			url: "ajq_getmailfriendform.php",
			data: poststr,
			dataType: "json",
   			success: function(jr){
//				$('#'+jr.respz.targetdiv).html(jr.respz.html)
	 			$(obj).after(jr.respz.html)
				$('#mf_submit').unbind()
					.click(function(){
							submitmailfriend( $(this).parent('form'),'mf_feedback')
							return false
							})
				$('.closebox').unbind().click(
						function(){$('#tellafriend').remove()
						$('#searchfieldselector').show()
				})

				$('#tellafriend').css('top',ypos-200)
				$('#searchfieldselector').hide()
   			}
 		});
}

function submitmailfriend(formobj,targetdiv) {
	$('#mf_feedback').html('<img src=tiny_red.gif>')
 	var poststr=$('#mailtofriend').formSerialize()+"&targetdiv=mf_feedback"
 	//TODO does ajq_saveform.php need a table var?
 	if (validateform(formobj)==0) {  //counts no of erroneous fields
 		logthis('<span class="removable">Validated. Submitting</span>')

		$.ajax({
   			type: "POST",
   			url: "ajq_mailfriend.php",
			data: poststr,
			dataType: "json",
   			success: function(jr){
				$('#'+jr.respz.targetdiv).html(jr.respz.html)
   			}
 		});
 	}
}
