$(document).ready(function(){
//	$('#topmenu_lower').find('div').css('border','1px solid yellow')
	// these anchors are setup in index.php as start values
	setClickable_incrementalsearchanchors('incsearchstyle')
	setClickable_getareadetailsanchors('getareadetails')

	DoenAjax_buildsearchbox('searchbox','no')  // fragment search
	$("#closejqfb").click(function(){$('.jqfeedback').remove()})

	// WHAT/WHERE
	var defaultareaforstats=$('#defaultareaforstats').val() // in index_leftcol.php
	DoenAjax_buildfullsearchcontrol(defaultareaforstats,'','') // now area_id ==> id of a geographical area
	
	$('#flashitem').html('<object classid="clsid:D27CDB6E-AE6D-11CF-96B8-444553540000" id="obj1" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0" border="0" width="600" height="250"><param name="movie" value="rentproperty_home.swf"><param name="quality" value="High"><embed src="rentproperty_home.swf" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" name="obj1" width="600" height="250"></object>');


	$("#tableformat").unbind().click(function(){
			if (!isloggedin()) {
				alert('You need to be logged in to download the data to xls format')
				return
			}
			$('#tabular').val('yes')
//			DoenAjax_execareafullsearch (formobj,pq,step,calledfromline)
			DoenAjax_execareafullsearch ($('#fullsearchform'),'',0,'14','yes');
		})
		.addClass('clickable')

	if ($('#getrecord').val()!=null) {
		setback('asb') // where else? maybe parent area? could be set in showmaxi
		$('#flashitem').remove()
		DoenAjax_showmaxi('listing','record_id','resultarea',$('#getrecord').val(),'yes','yes')
	}
	else if ($('#getto_area_id').val()!=null){
		var area_id=$('#getto_area_id').val()
		$('#persistenturl').val('area_id='+area_id+'&targetdiv=resultarea');
		setback($('#persistenturl').val())
		DoenAjax_execareafullsearch ('','yes','','28');
	}
	else {

/*		THESE ARE CHAINED, each firing the next from the success clause of its ajax call
		in rentsachart.js
		fetchtop10 only chains if areaid==undefined or < xx
*/
		var defaultareaforstats=$('#defaultareaforstats').val() // in index_leftcol.php
		fetch3mavg(defaultareaforstats,'yes')
//		fetchtop10 ()
//		fetchptytype('2')

		fetchcrumbs(1,'incsearchstartarea')

	}
// Doenajax_getareacontents_id_target($('#getrecord').val(),'resultarea')
// 	JT_init_additional("listmenuitem")
	$('#testbutton').click(function(){$('.smallsearch').show() })
//	$('#addlistingsearchboxarea').hide() //IE6 bug 

	$('#getto').click(function() {setasbfromurl_getto () }).addClass('clickable')
	$('#runstoreurl').click(function() {
						setasbfromurl_string ( $('#storeurl').val() )   	
					}).addClass('clickable')

	$('#showhistory').click(function() {
				var hm="i:"+historymatrixindex+"\n"
					for (key in historymatrix){
						hm +=historymatrix[key]+"\n"
					}
					}).addClass('clickable')

		$('#backbutton').click(function() { backbuttonclicked()}).addClass('clickable')
		$('#fwdbutton').click(function() { fwdbuttonclicked()}).addClass('clickable')
		setbackfwdbuttons()

		window.setTimeout('domarquee()',4000)
		
		$('#gogetrecbyid').click(function() { 
			 window.location='index.php?record_id='+ $('#getrecbyid').val()
				})
			.addClass('clickable')

		$('#getrecbyid').bind('keypress', function(event) {
						var code=event.charCode || event.keyCode;
						if(code == 13) {
							window.location='index.php?record_id='+ $('#getrecbyid').val()
						}
					})
});
 
function domarquee() {
	if ($.browser.msie) {
		 $('.mq').wrap('<marquee BEHAVIOR="SLIDE"></marquee>')
			.show()
			.css('margin-left',"8px")
	}
	else {
		var lm = parseInt($('.mq').css('margin-left'),10)
		var w =  parseInt($('.mq').css('width'),10)
		if (lm>500) {
			 $('.mq').css('width',100)
			 w = 100
		}

		if (lm>10) {
			lm -= 10
			w += 10
			$('.mq').show().css({'margin-left':lm,width:w,height:'16px'})
			window.setTimeout('domarquee()',100)
		}
	}
}

function setback(poststring){
	$('#goback_post').val(poststring)
	$('#goback_post','#follow_toback').unbind().click(function(){followback()})
}

function setbackfwdbuttons() {
// hide/show according to history data and pointer
//	$('#hmidx').html(historymatrixindex+'/'+historymatrix.length)
//	if (historymatrix.length>0)	$('#backbuttonarea').show()
	if ((historymatrixindex>=0) || (historymatrixindex<historymatrix.length-1) ) $('#backbuttonarea').show()
	
	if (historymatrixindex>0) $('#backbutton').show()
	else $('#backbutton').hide()

//     var isDetailView = document.URL.indexOf('record_id');
//  && !( (historymatrix.length==1)&&(isDetailView>0) )
    if (historymatrixindex==0) { 
        var backToProvinceLink = document.createElement('img');
        var oldBackButton = document.getElementById('backbutton');
        backToProvinceLink.setAttribute('alt', '[ <== ]');
        backToProvinceLink.setAttribute('id', 'backToProvinceButton');
        backToProvinceLink.setAttribute('onclick', 'javascript: gotoTopLevelIncSearch()');
        backToProvinceLink.setAttribute('src', 'buttons/back.png');
        document.getElementById("backbuttonarea").insertBefore(backToProvinceLink,oldBackButton);
    }else{
        var backToProvinceLinkButton = document.getElementById('backToProvinceButton');
        if (backToProvinceLinkButton) {
            var backToProvinceLinkParent = backToProvinceLinkButton.parentNode;
            backToProvinceLinkParent.removeChild(backToProvinceLinkButton);
        }
    }
	
	if (historymatrixindex<historymatrix.length-1) $('#fwdbutton').show()
	else $('#fwdbutton').hide()

}

function backbuttonclicked(){
	if (historymatrixindex>0) {
		historymatrixindex--
		setasbfromurl_string (historymatrix[historymatrixindex]+"&makehistory=no")
	}
	setbackfwdbuttons()
}

function fwdbuttonclicked(){
	if (historymatrixindex<historymatrix.length-1) {
		historymatrixindex++
		setasbfromurl_string (historymatrix[historymatrixindex]+"&makehistory=no")
	}
	setbackfwdbuttons()
}

// $persistenturl comes from ajq_fullsearch and could be in url as part of back button restore 
function setasbfromurl_getto () { // from #getto populated by php
	var s=''
	var asb='ID'
	var record_id='nil'
	var shndlr='nil'
	$('#getto').children('input').each(function() {
		var getkey=$(this).attr('name')
		var getval=$(this).val()
		if (getkey=='record_id') record_id=getval
		if (getkey=='shndlr') shndlr=getval
		var id=''
		var control=$('#fullsearchform')/*.find('#'+getkey+'div')*/.find('[@name='+getkey+']')
		if (control!=undefined) {
			control.val(getval)
			asb+='<br>{[@name='+getkey+']'+id+"}<br>"
		}
	})
	// which handler is best suited to restore this state?
//	DoenAjax_execareafullsearch($('#fullsearchform'),'','','66','yes')
 	exechistoryclick(shndlr,'yes',record_id) //area_id=38&propertytype=empty&prmin=empty&prmax=empty&rentduration=empty&furnishing=empty&added=-1&availablefrom=&so=hitolo&record_id=&step=0&tabular=no&targetdiv=resultarea

}



function setasbfromurl_string (url) { // from an url string passed
//	$('#getto').after(url)
	var urlmatrix = url.split('&')
	var asb='ID'
	var makehistory=''
	var shndlr='nil'
	var record_id='nil'
	for (key in urlmatrix) {
		var keypair=urlmatrix[key].split('=')
		var getkey=keypair[0]
		var getval=keypair[1]
		if (getkey=='shndlr') shndlr=getval
		if (getkey=='record_id') record_id=getval

		var id=''
		var control=$('#fullsearchform')/*.find('#'+getkey+'div')*/.find('[@name='+getkey+']')
		if(getkey=="makehistory") makehistory=getval  //if user is clicking back button
		if (control!=undefined) {
			control.val(getval)
		}
	}
	exechistoryclick(shndlr,makehistory,record_id)
	// makehistory==no if user is clicking back button
 //area_id=38&propertytype=empty&prmin=empty&prmax=empty&rentduration=empty&furnishing=empty&added=-1&availablefrom=&so=hitolo&record_id=&step=0&tabular=no&targetdiv=resultarea

}


function exechistoryclick(shndlr,makehistory,record_id) { // pass on to the correct handler to restore state
	if (shndlr!='nil') {
		if (shndlr=="fullsearch") DoenAjax_execareafullsearch($('#fullsearchform'),'','inplace','144',makehistory)
		else if (shndlr=="maxi")  DoenAjax_showmaxi('listing','record_id','resultarea',record_id,makehistory,'no')
	}
	else alert('no state handler set')
}

function clearstats() {

}

function followback(){
	var gobackto =$('#goback_post').val()
	if (gobackto=='') window.location.reload()
	else if (gobackto.indexOf('showmaxi')!=-1) {
		var recno=gobackto.split('=')[1]
		DoenAjax_showmaxi("listing",'record_id','resultarea',recno,'no','yes')
	}
	else if (gobackto=='asb') { //advanced search box, setback('asb')
//		DoenAjax_execareafullsearch (formobj,pq,step,calledfromline)	
		DoenAjax_execareafullsearch ($('#fullsearchform'),'','inplace','107','no');	}
	else if (gobackto=='closemaxi') {
			$('#resultarea').html('&nbsp;')
	}

}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

// function findPosX(obj)
//   {
//     var curleft = 0;
//     if(obj.offsetParent)
//         while(1) 
//         {
//           curleft += obj.offsetLeft;
//           if(!obj.offsetParent)
//             break;
//           obj = obj.offsetParent;
//         }
//     else if(obj.x)
//         curleft += obj.x;
//     return curleft;
//   }
// 
//   function findPosY(obj)
//   {
//     var curtop = 0;
//     if(obj.offsetParent)
//         while(1)
//         {
//           curtop += obj.offsetTop;
//           if(!obj.offsetParent)
//             break;
//           obj = obj.offsetParent;
//         }
//     else if(obj.y)
//         curtop += obj.y;
//     return curtop;
//   }


function getX(obj){
        return obj.offsetLeft + (obj.offsetParent ? getX(obj.offsetParent) : obj.x ? obj.x : 0);
    }
    function getY(obj){
        return (obj.offsetParent ? obj.offsetTop + getY(obj.offsetParent) : obj.y ? obj.y : 0);
    }



function backinstructions() {

$('#follow_toback').Tooltip({
	track: true,
	delay: 0,
	showURL: false,
	opacity: 1,
	fixPNG: true,
/*	showBody: " - ",
	extraClass: "pretty fancy",*/
	top: 5,
	left: 5
})


// $("#testdiv").position()
//	var obj = document.getElementById('follow_toback')
/*	var pp=findPos(obj)*/
// 	var xpos=getX(obj)
// 	var ypos=getY(obj)
 	$('#follow_toback').after('<div id="helptoback" style="float:right;position:relative;left:70px;">Use this link rather than the browser back button</div>')

//	$('#follow_toback').append('<span id="helptoback" style="float:left">Use this back button rather than the browser back button</span>')
	window.setTimeout('closebackinstructions()',4000)

}

function closebackinstructions() {
	
$('#helptoback').remove()
		$('#ftbimg')
			.click(function(){ followback() })
			.addClass('clickable')

}

function setClickable_incrementalsearchanchors(anchorclass) {
		// "crumbs".  WHAT/WHERE: adv srch box runs the search, let it know about this area_id
logthis('<span style="color:green;font-weight:bold">L155</span>:fs from inc anchor:'+anchorclass)

	$('.'+anchorclass).each(function(j) {
								// also highlight clicked area, remove old highlights
//		$(this).unbind("click").removeClass('incsearchclicked');

		$(this).click(function(){
//WHAT/WHERE
//				Doenajax_buildsearchincremental ($(this).attr("area_id"), $(this).attr("target"));
// target=incsearcharea	
// Put the area_id into asb, into input id=area_id_advanced, but input NAME = area_id
			if (!$.browser.msie ) {
				var area_id_attr="hidden"
				if (loggingon) area_id_attr="text"
//				$('#area_id_advanced').attr('type',area_id_attr)
				$('#area_id_advanced').val($(this).attr("area_id"))
				.next('span').html($(this).html())
				
			}
			else { 
				var xxx=$(this).attr("area_id")
				$('#area_id_advanced').val(xxx).next('span').html($(this).html())

			}
				$('#selectarealabel').children('.canhide').hide()

 			DoenAjax_execareafullsearch ($('#fullsearchform'),'',0,'56','yes'); //L434
				// set highlight for clicked one, gets taken away with new crumbs when fullsearch is done anyhow, but gets set in 
				// DoenAjax_execareafullsearch->success->fetchcrumbs->ajq_getcrumbs->dbfunct.php::crumbs
			$(this).addClass('incsearchclicked');
								})
				})
}

function setClickable_getareadetailsanchors(anchorclass) {
				$('.'+anchorclass).each(function(j) {
					$(this)	.unbind("click") 
							.click(function(){
							Doenajax_getareacontents_id_target($(this).attr("area_id"),$(this).attr("target"));
						})
				})
}

function setClickable_savesearch(anchorclass) {


				var anker = $('.'+anchorclass)
				$('.'+anchorclass).each(function(j) {
					$(this).unbind("click") 
					.click(function(){
						Doenajax_savesearch(this,$(this).attr("area_id"),$(this).attr("savetype"));
						})

					$(this).parents("form").children().not('.runfullsearch').each( function(tel){ 
						$(this).unbind("change")
						$(this).change(function() {//anker.fadeIn("slow")
									$('.'+anchorclass).show()
						$('#transient').remove()})
//				logthis(anchorclass+"=anker?"+anker)

						})

				})
//				.after('<div id="transient">You need to select at least one option above to be able to save the search criteria</div>')

				logthis("L87:savesearchbutton tied to change in controls")
}



function 	setClickable_runfullsearch(anchorclass) {
				$('.'+anchorclass).each(function() {
								$(this).unbind()
								.click(function(){
//							$("#resultarea").html('<img src=tiny_red.gif>')
 							DoenAjax_execareafullsearch($(this).parents("form"),'','','L88','yes')
													})
								.addClass('clickable')
											});
}											


function 	setClickable_resavesearch(anchorclass) {
				$('.'+anchorclass).each(function(j) {
								$(this).unbind("click") 
											// clear any existing clicks on page
								$(this).click(function(){
							DoenAjax_Resavefullsearch($(this).parents("form"),'','')
													})
											})
									.fadeIn("slow")
											;
}											

function posttoarray(poststring) {
	var postmtx=poststring.split('&')
	var postmtx3 = [];
	for (var i=0;i<postmtx.length;i++) {
		var postmtx2=tt=postmtx[i].split('=')
		var n=postmtx2[0]
		var v=postmtx2[1]
		postmtx3[n]=v
	}
	return postmtx3
}
//=============================differs from the one for usradmin. this looks by area, that by user=======

function Doenajax_getareacontents_recid_step (fromref,pmtablename,area_id,step,poststring) {
// NOTE poststring is sent as parameter since it reflects a navstrip anchor element
// seems the rest is not even necessary, but area_id is required for setupfetchedpage and banners, can this be extracted from poststring?
// it is actually setClickable_getareacontents_recid_step that sets up a useful poststring
//  ==> this poststring will contain the relevant step 
	if (area_id=='') {
		var postarray=posttoarray(poststring)
		area_id=postarray['area_id']
	}
	var tab
	if (document.getElementById('displaytype').checked) {
		tab="yes"
		poststring+="&tabular=yes"
	}
	else tab="no"
logthis('L91<br>'+poststring)
	$("#resultarea").html('<img src=rpspinbig.gif>') //targetdiv = resultarea, not always?
	$('#statsgenl2').html('<img src=rpspinbig.gif>')			
	$('#statsgenl').html('')			

		$.ajax({
   			type: "POST",
   			url: "ajq_getareacontents.php",   // [L151]
			data: poststring,
			dataType: "json",
   			success: function(jr){
				$('#statsgenl2').html(jr.respz.statsline)			
				$("#resultarea").html('')
				$('#'+jr.respz.targetdiv).html(jr.respz.html);
				$('#persistenturl').val(jr.respz.persistenturl)
				setupfetchedpage_getareacontents(area_id)
				//areaid and targetdiv set as attributes by ajq_searchincremental

				// navanchors cannot be set in prev function, it differs for inc and adv srch
				$('.navanchoractive').each(function(j) {
//						setClickable_getareacontents_recid_step(this, j);
						setClickable_navanchors_ww(this);
					})
   			}
 		});
		 DoenAjax_logbannerevent('area',area_id,'L104')
		 setback(poststring)

}


function setClickable_deletefullsearch (anchorclass) {
		$('.'+anchorclass).each(function(j) {
					$(this).unbind("click") 
					$(this).click(function(){
						DoenAjax_DeleteSavedSearch($(this).attr("record_id"))
					})
				})
}

function setClickable_viewdetail(anchorclass){  // typically .smallinput (View Detail)
		$('.'+anchorclass).each(function(j) {  // now this class belongs to an img
					$(this).unbind("click") 
					.click(function(){

						if (!isloggedin()) {
							alert('You need to be logged in to view more detail')
							return
						}

						$(this).attr('src','rpspinbig.gif')
						var recno=$(this).attr('recno')
						var targetdiv=$(this).attr('targetdiv')+"_alt"
						var tableidfield=$(this).attr('tableidfield')
//						DoenAjax_buildinput_for("listing",tableidfield,targetdiv,recno)	})
						DoenAjax_showmaxi("listing",tableidfield,targetdiv,recno,'yes','no')
						//move show/hide event linking to into DoenAjax_show
 //						to get timing right
						})
	    			.Tooltip({
						track: true,
						delay: 0,
						showURL: false,
						opacity: 1,
						fixPNG: true,
//						showBody: " - ",
//						extraClass: "pretty fancy",
						top: 5,
						left: 5
					})



				})

}


function setClickable_picinstrip(anchorclass){ //allow user to delete pics, "shortlist"
		$('.'+anchorclass).each(function(j) {
					$(this).unbind("click") 
						.click(function(){ 
							var record_id=$(this).parents('.picholder').attr('record_id')

            // a hack
            var temppic = $(this).attr('src')
            var imageIndex  = temppic.indexOf("image=");
            var imageValueIndex = imageIndex + 6;

            var picpath="resize_image.php?w=260&h=180&image="+temppic.substr(imageValueIndex,temppic.length);

// 							var picpath=$(this).attr('src')

							$('#primpic'+record_id)
								.attr('src',picpath)
/*								.width(300)
								.parent().width(300)*/
							}) //click function
						.attr('style','cursor:pointer')
				})
// NOTE: Changing id of primpic in rumini - check if it interferes here
}


function Doenajax_buildsearchincremental(area_id,targetdiv) { 
		// seems it is not used any more
	
		var poststr="forid="+area_id+"&targetdiv="+targetdiv
		$('#incsearcharea').prepend('<img src=rpspinbig.gif>').show()
		$('#advsrcharea').html('<img src=rpspinbig.gif>advanced search control').show()
		$.ajax({
   			type: "POST",
   			url: "ajq_searchincremental.php", 			//[L222]
			data: poststr,
			dataType: "json",
   			success: function(jr){
				$('#'+jr.respz.targetdiv).html(jr.respz.html);//target =incsearcharea
//WHAT/where	
				$('#advsrcharea').html(jr.respz.advsearchbox).show()
				setupcalendar() // _globals.js
				$('#persistenturl').val(jr.respz.persistenturl)
				$('#selectarea').hide()
				$('#resultarea').hide()
				setClickable_incrementalsearchanchors('incsearch')
				setClickable_getareadetailsanchors('getareadetails')
				$('#fetch3mavg').attr("area_id",area_id)
							.next('span').remove().end()
							.after('<span>'+jr.respz.areaname+'</span>')
//							.remove()
				fetch3mavg(area_id)
//				fetchptytype(area_id)
//				WHAT/WHERE always relevant, allways listings returned
// 				so call getareacontents anyway
//				if (jr.respz.execnow=='yes') {
		logthis('<span class=errormsg>L381:IncS->FS</span>')
//				$('.execnow').click()  // fires .getareadetails, L55, 
//				DoenAjax_execareafullsearch (formobj,pq,step,calledfromline);
				DoenAjax_execareafullsearch ($('#fullsearchform'),'',0,'248','yes'); //L434
/*				}
				else {
					get_stats_genl(area_id)

 				}*/
/*		replaced with WHAT/WHERE always on
		logthis('[rentsaL184]fetching advanced search control too')
		DoenAjax_buildfullsearchcontrol(area_id,'','') // now area_id ==> id of a geographical */				//areaid and targetdiv set as attributes by ajq_searchincremental

   			}
 		});
}

// similar in jquery_usradm.js, without graphs
function setupfetchedpage_getareacontents(area_id) {  
/*		navanchors cannot be set here, they differ for incremental and full searches
		$('.navanchoractive').each(function(j) {	setClickable_getareacontents_recid_step(this, j);})*/
		//areaid and targetdiv set as attributes by ajq_searchincremental
		setClickable_incrementalsearchanchors('incsearch')
		setClickable_getareadetailsanchors('getareadetails')
		setClickable_savesearch('savesearchstyle')
		setClickable_viewdetail('smallinput')
		$('#fetch3mavg').attr("area_id",area_id)
//		$("#simple").tableSorter();

//		fetch3mavg(area_id) == moved to fullsearch
//		fetchptytype(area_id)
//		get_stats_genl(area_id)
//WHAT/WHERE		fetchcrumbs(area_id,'incsearcharea')
	// advanced search control setup to save click, inside success of ajax for timing
		logthis('[rentsaL219]NOT fetching asb in sufp')
//		DoenAjax_buildfullsearchcontrol(area_id,'','') 
		// now area_id ==> id of a geographical area	
		// added to save click
}


function fetchcrumbs(area_id,targetdiv){  // usually target= incsearcharea
// largely replaced by getting crumbs in ajq_: fullsearch | searchincremental in order to accommodate counts for filtered searches
// so split fetching (ajax) and linking event handlers

// dont show breadcrumbs if ...
//  -- getting new listing, signalled by $('#newlisting').html()=='new' 
	if ($('#newlisting').html()=='new') return
	var poststr="area_id="+area_id+"&targetdiv="+targetdiv
	$("#"+targetdiv).html('<img src=rpspinbig.gif>').show()
		$.ajax({
   			type: "POST",
   			url: "ajq_getcrumbs.php",
			data: poststr,
			dataType: "json",
   			success: function(jr){
				setClickable_crumbs(jr.respz.crumbsup,jr.respz.crumbsdn,targetdiv)
   			}
 		});
}


function setClickable_crumbs(crumbsup,crumbsdn,targetdiv) {
	var cup=""
	if (crumbsup!=undefined) cup=crumbsup
	var cdn=""
	if (crumbsdn!=undefined) cdn=crumbsdn
//WHAT/WHERE
	$('#'+targetdiv).html(cup+cdn).show()
	setClickable_incrementalsearchanchors('incsearch')
	if (targetdiv!='incsearchstartarea') {
			$('#incsearchstartarea').hide()
			$('#startinstructions').hide() // remove start link
	}
	$('#'+targetdiv).show()
}


function gotoTopLevelIncSearch() {
    $('#incsearcharea').hide();
    $('#resultarea').hide();
    $('#backbuttonarea').hide();
    $('#startinstructions').show(); // remove start link
    $('#incsearchstartarea').show();
    var backToProvinceButton = document.getElementById('backToProvinceButton');
    backToProvinceButton.parentNode.removeChild(backToProvinceButton);
    backbuttonclicked();
    $('#backToProvinceButton').hide();
    // update graph
    var defaultareaforstats=$('#defaultareaforstats').val() // in index_leftcol.php
    fetch3mavg(defaultareaforstats,'yes')
}



function Doenajax_getareacontents_id_target(areaid,targetdiv) {
			// area = geo area, part of advanced search
	var tab
	if (document.getElementById('displaytype').checked) tab="yes"
	else tab="no"
	var poststr="area_id="+areaid+"&targetdiv="+targetdiv+"&tabular="+tab
	setback(poststr)

	$("#"+targetdiv).html('<img src=rpspinbig.gif>').show()
//	$('#statsgenl2').html('<img src=rpspinbig.gif>')
	$('#statsgenl').html('<img src=rpspinbig.gif>')
		$.ajax({
   			type: "POST",
   			url: "ajq_getareacontents.php",    //[L307] 
			data: poststr,
			dataType: "json",
   			success: function(jr){
				$('#statsgenl').html(jr.respz.statsline)
				$('#'+jr.respz.targetdiv).html(jr.respz.html);
				setupfetchedpage_getareacontents(areaid)
				
				// navanchors used to be in setupfetched page, 
				$('.navanchoractive').each(function(j) {
//						setClickable_getareacontents_recid_step(this, j);
						setClickable_navanchors_ww(this);
				})

				// advanced search control setup to save click, inside success of ajax for timing
//				logthis('[rentsaL289]fetching advanced search control too')
//				DoenAjax_buildareafullsearch_exselector('area_id') 
// called via setupfetchedpage_getareacontents already
				// area_id is id of selector, not of area	
				// added to save click
   			}
 		});
	DoenAjax_logbannerevent('area',areaid,'L267')
}

//============== to jquery_showlist.js 
function setClickable_getareacontents_recid_step (obj, i) {	
	alert('OLD')

			// for nav anchors
	var objid=$(obj).attr("id") // id = area_id
	domelement=document.getElementById(objid)
	var poststring=""
	for (var j=0;j<domelement.attributes.length;j++) {
		poststring+="&"+domelement.attributes[j].name+"="+domelement.attributes[j].value
	}
	$(obj).click(function(){ //fromref,pmtablename,recid,step
			//these attributes are set in (inter alia) navstripjq.php
			Doenajax_getareacontents_recid_step($(this).attr("fromref"),$(this).attr("pmtablename"), $(this).attr("area_id"),$(this).attr("step"),poststring)
		})
}

function setClickable_navanchors_ww(obj) { //WHAT WHERE, replaces old navanchor clicks
		$(obj)
			.unbind()
			.click(function(){ 
// move toward setting step in asb
				var step=$(this).attr("step")
//				document.getElementById("step_asb").value=step
				$('#step_asb').val(step)
 				DoenAjax_execareafullsearch ($('#fullsearchform'),'',step,'369','yes'); //369
			})

}

function DoenAjax_getareacontents_select(selectorid) {  // [L254]
	// this is from the selector generated from the search text fragment, with no advanced options selected
	// this must also paint the advanced search selector
	//extract the area_id from the hidden input box in the banner where the dropdown selector would have put it when clicked (fragsearch.js) and call the general function to get area contents
	if ($("#"+selectorid).val()=="") {
		alert('Please click on an area for your search (277)'+selectorid)
		return
	}
	Doenajax_getareacontents_id_target($("#"+selectorid).val(),'resultarea')
}

function DoenAjax_getareacontents_pq(selectorid) {
	//extract the area_id from the hidden input box in the banner where the dropdown selector would have put it when clicked (fragsearch.js) and call the general function to get area contents
	if ($("#"+selectorid).val()=="") {
		alert('Please click on an area for your search (286)')
		return
	}
	Doenajax_getareacontents_id_target($("#"+selectorid).val(),'resultarea')
}

//		buildusersearches from 	area_id
//							username (stored === pq) ?? not required to build full search control ??
//							navcontrol [area_id || username] step 
//												?? not required to build full search control ??


function DoenAjax_buildfullsearchcontrol(area_id,usn,step) {
	$('#area_id').val(area_id)  // post area_id (geo id) TO persistent control in banner
	$('#advsrcharea').html('<img src=rpspinbig.gif><br>Advanced search control').show()
	
	var poststr="targetdiv=advsrcharea&area_id="+area_id+"&searchtext="+$("#searchtext").val()
		$.ajax({
   			type: "POST",
   			url: "ajq_buildusrsearches.php",
			data: poststr,
			dataType: "json",
   			success: function(jr){
				$('#'+jr.respz.targetdiv).html(jr.respz.html).show()
				setupcalendar() // _globals.js
				setClickable_runfullsearch('runfullsearch')
				setClickable_savesearch('savesearchstyle')
				$('.register').each(function(j) {  		//button, 
								$(this).unbind("click") 	// clear any existing clicks on page
								$(this).click(function(){ window.location="signup.php"
													})
								});
				$('#advlogin').unbind().click(function(){$("#menu_login").click()})
						.addClass('clickable')
				$('.deletesearch').each(function(j) {  		//button, 
								$(this).unbind("click") 	// clear any existing clicks on page
								$(this).click(function(){ 
										DoenAjax_DeleteSavedSearch($(this).attr('record_id'))
													})
								});
   			}
 		});
		
}

function DoenAjax_buildareafullsearch_exselector(selectorid) { // [L310]
	// selectorid should point to hidden input box in banner with area_id
	// this calls up an advanced search box full of dropdowns to be painted, from dbfunct.php
	// if called from textfrag=>selector, look in #area_id for area_id
	// if automatically generated from incremental search, look in .area_id_holder
	// full search first?
	var area_id=""
	area_id=$("#"+selectorid).val() 
	logthis(selectorid+"\n"+area_id)
	if ((area_id=="") ||(area_id==null)) {
		area_id=$('.area_id_holder').html()
		if ((area_id=="") ||(area_id==null)) {
			alert('Please click on an area for your search (342)')
			return
		}
		else logthis('rentsaL310 using inc srch areaid')
	}
	else  logthis('rentsaL310 using txtfrg=>slct srch areaid')

		DoenAjax_buildfullsearchcontrol(area_id,'','') // now area_id ==> id of a geographical area
			//calling function that needs  area_id
//							username (stored === pq)
//							navcontrol [area_id || username] step
}


function DoenAjax_execareafullsearch (formobj,pq,step,calledfromline,makehistory) {
	//	outputs area contents in shortlist format (rumini)
	//	if a persistent query is executed, do it, else send query paramaters by serializing select control inside form 
	//	if (document.getElementById("persistentquery"))
	//	var pq=document.getElementById("persistentquery").innerHTML //set by login function
	//  step="inplace" if the #step_asb has been set, eg for goback

	// stats for statsline at top: #statsgenl comes with ajax return
	$('#flashitem').remove()
//	$('#chartarea').remove()
//	$('#helpdisplay').remove()
	if (step=='inplace') step=$('#step_asb').val()

	logthis("L439 execareafullsearch<br>Form:"+$(formobj).attr('id')+"<br>pq="+pq+"<br>step="+step+"<br>call="+calledfromline)

	var targetdiv="resultarea"

	if ((pq) && (pq!="")) {
	// under pq there are two options : pq saved as sql in #persistentquery
	// and poststring saved in persistenturl, a hidden input in banner
	// the latter must be phased in 
		var pqurl=$('#persistenturl').val()
		if (pqurl!="") {
			var poststr=pqurl
			var toreplace="&"
			var replacewith='<br>&'
			var newpost=poststr.replace(/&/g, replacewith)
//			logthis('Pqurl post<br>'+newpost)
		}
		else {
			var pqsaved=$('#persistentquery').html()
			var poststr="pq="+encodeURIComponent(pqsaved)+"&step="+step+"&targetdiv="+targetdiv
//			logthis('Pqsql post<br>'+poststr)
		}
	}
	else {
		pq="nopq" 
//	var poststr="step="+step+"&pq="+encodeURIComponent(pq)
//		$("#"+targetdiv).html('<img src=rpspinbig.gif>')
//		here step_asb gets posted rather than simply step
		var pmin = $('#prangeprmin').val()
		var pmax = $('#prangeprmax').val()
	
		if (pmax<=pmin) {
			if ((pmin!='empty') && (pmax!='empty')) {
				alert('Max price must be larger than Min price')
				return
			}
		}

 		var poststr=$(formobj).formSerialize()+"&targetdiv="+targetdiv
		if ($.browser.msie) poststr+="&step="+step

/*		var toreplace="&"
		var replacewith="\n&"
		var newpost=poststr.replace(/&/g, replacewith)
		alert(newpost)*/
	}

	var tabular=$('#tabular').val()
	if (tabular=="yes" ) { 
			// post normally, if tabular == yes the headers in ajq_fullsearch will be 
			// set by userfunct.outputcsv() and cause download to start 
		$('#fullsearchform').attr('action','ajq_fullsearch.php').submit()
		$('#tabular').val('no')
		$('#fullsearchform').attr('action','')
		return false
	}

	$("#resultarea").html('<img src=rpspinbig.gif>').show() //targetdiv = resultarea
	$('#statsgenl').html('<img src=rpspinbig.gif>') 
	$('#ptytypediv').html('<img src=rpspinbig.gif><br>Property Type Breakdown')
		$.ajax({
   			type: "POST",
   			url: "ajq_fullsearch.php",
			data: poststr,
			dataType: "json",
   			success: function(jr){
				
				$('#selectarea').html('')

				$('#statsgenl').html(jr.respz.statsline)	
				$('#'+jr.respz.targetdiv).html(jr.respz.html);
				$('#advsrcharea').html(jr.respz.advsearchbox)
				setupcalendar() // _globals.js
				$('#persistenturl').val(jr.respz.persistenturl);
				if (makehistory=="yes") { 
					//. dont reset history if user is clicking back button
					historymatrixindex++
					historymatrix[historymatrixindex]=jr.respz.persistenturl+'&shndlr='+jr.respz.statehandler
					var tt=historymatrix.length-historymatrixindex
					if (tt>1) historymatrix.splice(historymatrixindex+1,tt)
					setbackfwdbuttons()
				}

				$('.register').each(function(j) {  //button, 
								$(this).unbind("click") // clear any existing clicks on page
								$(this).click(function(){ window.location="useradmin.php"  })
											});
				var tel
				$('.navanchoractive').each(function(j) {	
									setClickable_navanchors_ww(this) //WHAT/WHERE
				//							$(this).unbind("click") 
											// clear any existing clicks on page
				//							setClickable_pq_step(this,j);
											tel=j
											});
				logthis('Tied event x:\n'+tel)
				setback('asb')

				//enable the breadcrumbs inside each rumini as well as other items
				// cant do navanchors there, would clash with the above
				setupfetchedpage_getareacontents(jr.respz.area_id)		
				setClickable_runfullsearch('runfullsearch')  // not in setupfetched....

				//WHAT/WHERE
				//replace fetchcrumbs with already sent crumbs, but have it set clickable
//				fetchcrumbs(jr.respz.area_id,'incsearcharea')  =replaced
				setClickable_crumbs(jr.respz.crumbsup,jr.respz.crumbsdn,'incsearcharea')

// property type breakdown comes as stats with each search, already in html make these clickable
				$('#ptytypediv').html(jr.respz.ptytypebreakdown)
				$('.ptylink').each(function(){
					$(this).unbind()
					 	.click( function(){
						// to make things simpler, hack the persistenturl
					// IE messes with anchor <a> tag (puts http in there), so the url is still a "title" attribute
							$('#persistenturl').val($(this).attr('title')+'&ptytypepost=yes&targetdiv=resultarea');
							 setback($('#persistenturl').val())
							DoenAjax_execareafullsearch ('','yes','','631');
							return false; //this is an anchor tag
						})
				})


//			setClickable_incrementalsearchanchors('incsearch')  //
//			in this context used for breadcrumbs (incremental) inside each rumini
//			setClickable_getareadetailsanchors('getareadetails') // in setupfetched..

			$('#tabular').val('no')

			$('.bumpupfeedback').remove()

			$('#3mavg').html(jr.graph.threemoavg)
			$('#threemavgcaption').html(jr.graph.caption)

			$('#3mavg').find('table').css('margin','auto')
			
			if (jr.respz.lvl!=4) fetchtop10 ('no',jr.respz.area_id)
			else cleartop10()
			// both functions in rentsachart.js

			//DoenAjax_logbannerevent('area',jr.respz.area_id,'L867')
			restoretimeout()

   			} //success
//			,
//			error: function (xmlhttpobject,errmessage,exobj) { alert(errmessage);	}
 		});
}

function setClickable_pq_step(obj,j) {
	$(obj).click(function(){ //fromref,pmtablename,recid,step
			//these attributes are set in (inter alia) navstripjq.php
			DoenAjax_execareafullsearch ('',"yes",$(this).attr('step'),'L410')
		})
}


function Doenajax_savesearch(obj,area_id,savetype) {
/*	alert("saving search for area_id:"+area_id+'\n'+savetype)*/
	if (savetype=="pq") {
		var pqsaved=$('#persistentquery').html()
		var poststr="pq="+pqsaved
		logthis('Pq post\n'+poststr)
	}
	else if (savetype=="serialize") {
		$(obj).after('<img id="waiting_savesearch" src="rpspinbig.gif">')
		var formobj=$(obj).parents("form")
 		var poststr=$(formobj).formSerialize()	//+"&targetdiv="+$(formobj).attr('id')
		logthis("saving search with post="+poststr)
//		return
		$.ajax({
   			type: "POST",
   			url: "ajq_saveusersearch.php",
			data: poststr,
			dataType: "json",
   			success: function(jr){
/*   				$('#'+jr.respz.targetdiv).html(jr.respz.feedback);*/
				$(formobj).find(".resavefullsearch").fadeIn("slow") //only in user searches
				$('#waiting_savesearch').prev('.savesearchstyle').hide()				.after('<div id="transient">'+jr.respz.feedback+'</div>')

				$('#waiting_savesearch').remove()
   			}
		});
	}
}


function DoenAjax_showmaxi(table,tableidfield,targetdiv,recno,makehistory,showstats)	{
// also updates records of viewing for : Logon profile that list the lister's portfolio and viewings he has had per listing
var innewpage="yes"

	var poststr="table="+table+"&tableidfield="+tableidfield+"&recno="+recno+"&targetdiv="+targetdiv+"&innewpage="+innewpage
		$.ajax({
   			type: "POST",
   			url: "ajq_showmaxi.php",
			data: poststr,
			dataType: "json",
   			success: function(jr){
				if	(innewpage!="yes") $('#'+jr.respz.targetdiv)  //this will open detail in existing div
				else {	$('#resultarea').html(jr.respz.html).show()
					  // this will open detail in results area
				}
					//	$('#mainpanel')  //<this will open detail in "new page"
				setClickable_picinstrip('shortlist')
				// setback() already set to 'asb', now put area_id in asb, it will have been passed on by php
				$('#area_id_advanced').val(jr.respz.area_id).next().html(jr.respz.areaname)
					.end()
					.prev('.fieldlabelsearch_m').html('Suburb')
				putinbasket(recno,'addtoview',$('.basket'),jr.respz.area_id )

				$('.putinb').unbind()
						.click(function(){
							putinbasket($(this).attr('record_id'),'addtobasket',this,jr.respz.area_id  )
						})
						.addClass('clickable')

				$('.takefromb').unbind()
						.click(function(){
							DoenAjax_deletebasketitem($(this).attr('record_id'),setinmaxi)
						})
						.addClass('clickableplain')
								

				$('.contactowner').unbind()
					.click(function(evt){ 
						$('.contactowner_form').remove()
						contactowner(this,recno,evt.pageX,evt.pageY) // in jquery_login
						})
					.addClass('clickable')

				$('.reptunac').unbind()
					.click(function(evt){ 
						$('.contactowner_form').remove()
						reptun(this,recno,evt.pageX,evt.pageY) // in jquery_login
						})
					.addClass('clickable')

				if (innewpage=="yes") {
					$('.backrumini').remove()
//					$('.smallinput').hide() //  actually not shown again since back reloads
// 					$('.rumaxicontainer').prepend('<div id="follow_toback" class="backinmaxi" ><img src="buttons/back.png" id="ftbimg" alt="back" title="Use this back button"></div>')
					
					$('#ftbimg')
						.click(function(){ followback() })
						.addClass('clickable')
					
					backinstructions()
				}
				else {	$('.smallinput') // not implemented, IE6 gets lost
							.unbind("click") 
							.click(function(){ 
									$('#'+targetdiv).slideToggle('slow')
								})
//							.val('Show/Hide')
							.attr('src','buttons/show_hide.png')
				}

				// set history
				if (makehistory=="yes") { //. dont set history if user is clicking back button
					historymatrixindex++
					historymatrix[historymatrixindex]=jr.respz.persistenturl+'&shndlr='+jr.respz.statehandler
					var tt=historymatrix.length-historymatrixindex
					if (tt>1) historymatrix.splice(historymatrixindex+1,tt)
					setbackfwdbuttons()
				}
//	does stats per one listing maxi make sense?
//alert('ss'+showstats+"\n"+jr.respz.area_id)
				if (showstats=='yes') {
					fetch3mavg(jr.respz.area_id,'yes') 
					// setup this area for chaining procedures to know
					$('#defaultareaforstats').val(jr.respz.area_id)
					fetchcrumbs(jr.respz.area_id,'incsearchstartarea')
				}

// who viewed my listing
				$('.whoviewed').unbind()
					.click(function(evt){ 
						$('.whoviewedholder').remove()
						whoviewedmylisting_putform(this,recno,evt.pageX,evt.pageY,0) // in jquery_login
						})
					.addClass('clickable')



			}
		});
}


function putinbasket(record_id,dowhat,targetobj,area_id) {
	if (dowhat=="addtobasket") $(targetobj).after('<div id="waiting"><img src="rpspinbig.gif"></div>')
//	$('#putinbfeedback').remove()
	var poststr="record_id="+record_id+"&baskettxtype="+dowhat+"&area_id="+area_id
		$.ajax({
   			type: "POST",
   			url: "ajq_putinbasket.php",
			data: poststr,
			dataType: "json",
   			success: function(jr){
				if (dowhat=="addtobasket") {
					$('#basketsection').html(jr.respz.maxisection)
					$('.takefromb').unbind()
							.click(function(){
								DoenAjax_deletebasketitem($(this).attr('record_id'),setinmaxi)
							})
							.addClass('clickableplain')
					$('#waiting').remove()
				}
/*				$(targetobj).after(jr.respz.html)
				if (dowhat=="addtobasket") {
					$('#putinb').html(' Remove from basket.')
					$(targetobj).unbind().click( function() { 
						DoenAjax_deletebasketitem(record_id,setinmaxi)  })*/
				}
		});
}

function setinmaxi() {
	var poststr="record_id="+$('#basketsection').attr('record_id')
		$.ajax({
   			type: "POST",
   			url: 'ajq_getmyhistory.php',
 			data: poststr,
			dataType: "json",
   			success: function(jr){
				$('#basketsection').html(jr.respz.maxisection)
				$('.putinb').unbind()
						.click(function(){
							putinbasket($(this).attr('record_id'),'addtobasket',this )
						})
						.addClass('clickable')
			}
		})

}

/*function DoenAjax_buildinput_for(table,tableidfield,targetdiv,recno) => jquery_tables.js
*/
function fetchptytype(area_id) {

	logthis("fetch prop type for "+area_id)
	var targetdiv="ptytypediv"
	$("#"+targetdiv).html('<img src=rpspinbig.gif>')
		$.ajax({
   			type: "POST",
   			url: "ajq_ptytype.php",
			data: "area_id="+area_id+"&targetdiv="+targetdiv,
			dataType: "json",
   			success: function(jr){
				$('#'+jr.respz.targetdiv).html(jr.respz.html)
				// clicking on a property type selects listings of that property type from the area shown
				// it disregards other advanced search options, 
				// call the advanced search function: DoenAjax_execareafullsearch (formobj,pq,step,calledfromline)
				// NOTE: should advanced search need to be included, simply serialize adv search options
				// to make things simpler, hack the persistenturl
				$('.ptylink').each(function(){
					$(this).unbind()
					 	.click( function(){
						// to make things simpler, hack the persistenturl
					// IE messes with anchor <a> tag (puts http in there), so the url is still a "title" attribute
							$('#persistenturl').val($(this).attr('title')+'&ptytypepost=yes&targetdiv=resultarea');
							 setback($('#persistenturl').val())
							DoenAjax_execareafullsearch ('','yes','','631');
							return false; //this is an anchor tag
						})
				})
   			}
 		});

}

