var msiehtml='';

$(document).ready(function(){
//		$('#aboutusbrief').remove()

		$("#menu_login").click(function(){
			if (( $('#persistentusername').val()=='' )  || ($('#persistentusername').val()=='nil'))
			{
				DoenAjaxLoginbox('expanded')
			}
			else 	DoenAjaxLogoff()
		})

		$('#ld_login').unbind()
						.click(function() {  DoenAjaxLoginbox('expanded') })

		$('#ld_logoff').unbind()
						.click(function(){
									 DoenAjaxLogoff() })





	$('#showcurrentareaid').unbind().click(function(){
		var currentareaid1=$('#area_id').val()
		var currentareaid2=$('.area_id_holder').html()
		$('#showcurrentareaid').children('span').html(currentareaid1+'|'+currentareaid2)
		})

	$('#listmenuitem')
			.unbind('click')
			.click(function(){

				if ($("#all").attr("name")!="index") {
					window.location="index.php?newlisting=yes"
					return false;
				}
				else {
					DoenAjax_startnewlisting()
					return false;
				}
			  })

	if ($('#newlisting').html()=='new') {
		if  ($('#searchbox').html()=="") window.setTimeout('restart_newlisting()',1000)
		else DoenAjax_startnewlisting()  //newlisting is a div in index.php
	}

	$("#listinginfo")
		.unbind("click")
		.click(function(){
			helptext('newlisting')
		})
	  .addClass('clickable')

	var wherearewe=$('#all').attr('name')

	$('#menu_'+wherearewe).parent().addClass('activemenuitem')


	$('#historyanchor').unbind().click(function(){getmyhistory()})

	$('#mylogo').unbind().click(function(){mylogo()})

	$('#myuserrecord').unbind().click(function(){myrecord()})

	if (wherearewe=='useradmin') {  // maybe others too, index gets set up in php
					init_leftmenu ('L65')
					init_topmenu()
	}

	setupstoredsearches($("#persistentusername").val())

	$('#allborder').unbind().click(function(){ $('div').addClass('borderall')})
		.addClass('clickable')
	$('#allunborder').unbind().click(function(){ $('.borderall').removeClass('borderall')})
		.addClass('clickable')

	if (loggingon) {
		$('.jqfeedbackholder').removeClass('dbg')
		$('.jqfeedback').removeClass('dbg')

	}
	else {
		$('.debugblock').remove()
		$('#tempfeedback').remove()
	}

	$('#timeoutwarn').unbind().click(function() { pollserver() })
		.addClass('clickable')
		.hide()
	if (( $('#persistentusername').val()!='' )  && ($('#persistentusername').val()!='nil')) window.setTimeout("warntimeout()",throbinterval)
});


function restart_newlisting() {
	logthis('waiting for searchbox')
		if  ($('#searchbox').html()=="") window.setTimeout('restart_newlisting()',1000)
		else DoenAjax_startnewlisting()
}

function logthis (what) {
	if (!loggingon) return  //global
	$("#jqfeedbackholder").append('<div class=jqfeedback>'+what+'</div>')
}



function DoenAjaxLogin(waar) {
	var poststr="usn="+$('#ajxusn').val() + "&pwd="+$('#ajxpwd').val() + "&waar="+waar+"&remember="+$('#remember').val()
//alert($('#remember').val())
	$('.logon').children('img').attr('src','rpspinbig.gif')
		$.ajax({
   			type: "POST",
   			url: "ajq_login.php",
			data: poststr,
			dataType: "json",
   			success: function(jr){
				scrollTo(0,0)
				$('.logon').children('img').attr('src','buttons/login.png')

				if (jr.respz.ok=="yes"){

var wherearewe=$('#all').attr('name')
//if ((wherearewe=='useradmin') || ($.browser.msie)) window.location.reload(true)

if (wherearewe=='signup')  {
			// admin users dont have any need for signup form
			if (jr.respz.level=='admin') window.location='useradmin.php'
			else window.location='signup2.php'  //remove usn paramater if exists
			}

// if (wherearewe!='index')  {
//     window.location.reload(true);
// } else {
    // if on the homepage, redirect to proper landingpage on login.
    if (jr.respz.utype == 'tenant') {
        window.location = 'tenants.php';
    } else if (jr.respz.utype == 'landlord') {
        window.location = 'landlords.php';
    } else if ((jr.respz.utype == 'rea') || (jr.respz.utype == 'agent')) {
        window.location = 'agents.php';
    } else if (jr.respz.utype == 'investor') {
        window.location = 'investors.php';
    }
// }

		// IE6 crashes for unknown reason if new listing is added and user logs out
					setupstoredsearches(jr.respz.username)

					DoenAjaxLoginbox("collapsed")
					$('#menu_login').html('log off')
						.unbind()
						.click(function(){  DoenAjaxLogoff() })
// hide?
					$("#persistentusername").val(jr.respz.username) //needs to have change event
					$("#persistentlevel").attr("level",jr.respz.level)
					$("#persistentutype").val(jr.respz.utype)
					init_leftmenu ('L132')
					init_topmenu()
					$('#logindisplay').html('You are logged in as '+jr.respz.username+' <br><span id="ld_logoff" class="clickable"> log off</span>')
					$('#ld_logoff').unbind()
						.click(function(){  DoenAjaxLogoff() })

	//				resetclick_listmenu()
					restoretimeout()
					window.setTimeout("warntimeout()",throbinterval)
				}
				else {
	// bigger login box now moves in under flash, so lift it up
					$('#loginbox').css('top','130px')
					$("#loginfeedback").html(jr.respz.feedback)
					$("#loginusn").html(jr.respz.username)
					$("#loginlevel").html(jr.respz.level)

					$('#logindisplay').html('You are not logged in  <br><span id="ld_login" class="clickable">log in</span>')
					$('#ld_login').unbind()
						.click(function() {  DoenAjaxLoginbox('expanded') })


				}

   			}
 		});

}

function DoenAjaxLogoff(auto) {
	var poststr="auto="+auto
		$.ajax({
   			type: "POST",
   			url: "ajq_logoff.php",
			data: poststr,
			dataType: "json",
   			success: function(jr){
                        $("#ld_logoff").html('<img src=rpspinbig.gif>').show()

// if logged off and calendar is used in IE, it crashes!  this is the only way to refresh menus after logging off
		var wherearewe=$('#all').attr('name')
		if (wherearewe=='useradmin') {
				if ($.browser.msie) {
					window.location = 'index.php'
					return
					}
		}
		if (wherearewe=='tableview2') {
					window.location = 'index.php'
					return	false
		}


				logthis("#logoff\n"+jr.respz.feedback)
				$("#persistentusername").val("")
				$("#persistentutype").val("")
				$("#persistentlevel").attr("level",'')
				init_leftmenu ('L169')
				init_topmenu()
				scrollTo(0,0)

        // if on landingpages during logoff
        if ((wherearewe == 'index') || (wherearewe == 'agents') || (wherearewe == 'investors') || (wherearewe == 'landlords') || (wherearewe == 'tenants')) {
            // reload page in order to reset everything
            window.location.reload(true);
        } else {
            // redirect to homepage
            window.location = 'index.php';
        }

// document.getElementById('logoffDiv').innerHTML = 'You are not logged in  <br><span id="ld_login" class="clickable">log in</span>';
//                 document.getElementById('logoffDiv').parentNode.removeChild('logoffDiv');
// alert(document.getElementById('footer').innerHTML);
// 				$('#loginbox').hide()
// 				$('#menu_login').html('log in')
// 						.unbind()
// 						.click(function(){  DoenAjaxLoginbox('expanded') })
// 				$('#logindisplay').html('You are not logged in  <br><span id="ld_login" class="clickable">log in</span>')
// 				$('#ld_login').unbind()
// 						.click(function() {  DoenAjaxLoginbox('expanded') })
   			}
 		});
}

function DoenAjaxLoginbox(expanded) { //gets html for the login box
								// sets current logged on status
	if (expanded=="collapsed") {
		if ($.browser.msie ) {
	//		$('select').addClass('hidemsieselectors')
			$('#area_id_selectnewlisting').removeClass('hidemsieselectors')
		}
		$("#loginbox").hide()
		return
	}
	var poststr="expanded="+expanded

	$("#loginbox").html('<img src=rpspinbig.gif>').show()
		$.ajax({
   			type: "POST",
   			url: "ajq_loginbox.php",
			data: poststr,
			dataType: "json",
   			success: function(jr){
//				logthis("#loginbox="+expanded)


			if ($.browser.msiex ) {
					msiehtml=jr.respz.html
					window.setTimeout('ieslow()',2000)
				}
			else {
				$("#loginbox").html(jr.respz.html).show()
				$('#ajxusn')[0].focus()
				$(".logfunctions").click(function(){DoenAjaxLoginbox("expanded")})
				$(".logoff").click(function(){DoenAjaxLogoff()})
				$(".logon").click(function(){DoenAjaxLogin()})

				$('#ajxusn').bind('keypress', function(event) {
						var code=event.charCode || event.keyCode;
						if(code == 13) {
							$('#ajxpwd')[0].focus()
						}
				})

				$('#ajxpwd').bind('keypress', function(event) {
						var code=event.charCode || event.keyCode;
						if(code == 13) {
							DoenAjaxLogin()
						}
				})

				$(".closelog").click(function(){DoenAjaxLoginbox("collapsed")})
				$("#forgotpwd").unbind('click')
							.click(function(){ DoenAjax_fetchpwdquest()  })
			}
//				JT_init_additional("forgotpwd")

				if (jr.respz.loggedstatus=="nil") $("#savedsearchesanchor").hide()
				else {

					setupstoredsearches(jr.respz.loggedstatus)
				}

				$('#persistentusername').val(jr.respz.username)
				$('#persistentlevel').html(jr.respz.level)
				init_leftmenu('login228')
				init_topmenu()
				scrollTo(0,0)
   			}
 		});
}

function ieslow() {
				$("#loginbox").html(msiehtml).show()
				$(".logfunctions").click(function(){DoenAjaxLoginbox("expanded")})
				$(".logoff").click(function(){DoenAjaxLogoff()})
				$(".logon").click(function(){DoenAjaxLogin()})
				$(".closelog").click(function(){DoenAjaxLoginbox("collapsed")})
				$("#forgotpwd").unbind('click')
							.click(function(){ DoenAjax_fetchpwdquest()  })


				$('#area_id_selectnewlisting').addClass('hidemsieselectors')
//		$('select').removeClass('hidemsieselectors')
}

function setupstoredsearches(usn) {
		if ((usn==undefined) || (usn=="")) {
			logthis('HIDE.setupusersearches:'+usn)
			$("#savedsearchesanchor").hide()
		}
		else {
			if ($("#all").attr("name")=="useradmin") {
/*					$("#savedsearchesanchor")
					.attr("usn",usn)
					.html("Stored Searches (home)")
					.click(function(){
						window.location="index.php?savedsearches=yes&usn="+usn
						})
					.show()*/
			}

			else {
					$("#savedsearchesanchor")
					.attr("usn",usn)
					.html("Searches & Email Alerts")
					.click(function(){
						DoenAjax_getusersearches(usn) //tables
						})
					.show()

			logthis('setupusersearches:'+usn)
			}
		}
}

function DoenAjax_fetchpwdquest () {
//		$('#ajxpwd').hide().parent().prev().hide()
//alert('x')
	var usn=$('#ajxusn').val()
	if (usn=='') {
		alert('Please enter your username')
		$('#forgotinstruct').addClass('errormsg')
		$('#loginusernamelabel').addClass('errormsg')
		$('#loginbox').children('.hideforgot').hide()
		$('#loginfeedback').html('')
		return
	}

	var poststr="usn="+usn
		$.ajax({
   			type: "POST",
   			url: "ajq_getpwdquest.php",
			data: poststr,
			dataType: "json",
   			success: function(jr){
				$('#loginfeedback').html(jr.respz.feedback)
				$('#loginfeedback').after(jr.respz.pwdansholder)
				$('#loginbox').css('top','130px')
				if (jr.respz.ok=='yes') {
					$('#loginbox').children('.hideforgot').add('.fieldrowforgot').hide()
					$('#pwdquest').html(jr.respz.question)
					$('#getforgottencontainer').show()
					$('#sendpwdquest').show()
							.unbind("click")
							.click(function(){DoenAjax_sendpwdans() })
				}

   			}
 		});
}

function DoenAjax_sendpwdans () {
	$('#loginfeedback').html('')
	var poststr="usn="+$('#ajxusn').val()+"&pwdans="+$('#pwdans').val()
		$.ajax({
   			type: "POST",
   			url: "ajq_sendpwdans.php",
			data: poststr,
			dataType: "json",
   			success: function(jr){
				$('#loginfeedback').html(jr.respz.feedback)
				if (jr.respz.ok=='yes') {
					$('#getforgottencontainer').hide()
					$('#loginbox').children('.hideforgot').add('.fieldrowforgot').remove()
				}
   			}
 		});
}

function isloggedin() {
	if (( $('#persistentusername').val()!='' )  && ($('#persistentusername').val()!='nil')) return 	true
	else return false
}

//=================================================
function init_leftmenu (fromline) {
	var plevel=$('#persistentlevel').attr('level')
	var utype=$('#persistentutype').val()

//the persistent username and level will have been set by jscript on login or by php on request
		logthis('init_leftmenu'+fromline+"\n"+$('#persistentusername').val()+"\n"+$('#persistentlevel').html())

	if (isloggedin()) {
		$('#getmylistings'). unbind('click')
					    .click(function() {Doenajax_getuserlistings ('','0')} )
					    .show()
	}
	else $('#getmylistings').hide()

//alert($('.calendarButton').html())
//	if ($.browser.msie ) return

	if ( plevel!=undefined ) {
		if ( (plevel=='public')  || (plevel=='provisional') ){
			    $('.userlevel').show()
			    $('.adminlevel').hide()
			    $('.corplevel').hide()
		}
		else if ((plevel=='corporate' ) || (plevel=='2' )) {
			    $('.userlevel').show()
			    $('.corplevel').show()
			    $('.adminlevel').hide()
				$('#getmyareas').unbind('click')
						    .click(function() {Doenajax_builduseraccount ('users_areas','0') } )
		}
		else if (plevel=='admin')  {
		    $('.adminlevel').show()
		    $('.corplevel').show()
		    $('.userlevel').show()
			$('#getuserlist')
				.unbind('click')
			   	.click(function() {
					if (document.getElementById('su_textfragholder'))	$('#su_textfragholder').remove()
					Doenajax_builduserview_list ('users','0')
				})
			$('#bannerstats')	.unbind('click')
						    	.click(function() {window.location="admin/bannerlog.php" } )

			$('#getmyareas').unbind('click')
						    .click(function() {Doenajax_builduseraccount ('users_areas','0') } )
		}
		else { // some other arb level

			$('#getmyareas').unbind('click')
						    .click(function() {alert('Your user privileges may need to be confirmed') } )
			    $('.adminlevel').hide()

				if (utype!='landlord') {
			    	$('.corplevel').hide()
				}
		}


	}
	else { // undefined => non logged in user
		    $('.adminlevel').hide()
		    $('.corplevel').hide()
		    $('.userlevel').hide()
		    $('.reatype').hide()
		    $('.llord_rea').hide()

	}


	if (plevel=='admin') {
		$("#menu_upload").show()
	}
	else $("#menu_upload").hide()

}

function init_topmenu() {
	var plevel=$('#persistentlevel').attr('level')
	if (plevel==undefined) plevel='nil'

	var utype=$('#persistentutype').val()
	if (utype==undefined) utype='nil'

	$('.corpplus').add('.admintopmenutab').hide()

	if ( $('#persistentlevel').attr('level')=='admin')
		 $('.corpplus').add('.admintopmenutab').show()

	if ($('#persistentlevel').attr('level')=='corporate' )  $('.corpplus').show()

	if  (isloggedin()) $('#menu_signup').children('a').html('my details')
	else $('#menu_signup').children('a').html('signup')

	if ((utype=='landlord') || ( plevel=='admin' ))	$('.llord').show()
	else 	$('.llord').hide()
	if ((utype=='landlord') || ( plevel=='admin' ) || ( utype=='rea' )) $('.llord_rea').show()
	else 	$('.llord_rea').hide()


	if  (isloggedin()) $('.loggedinonly').removeClass('noshow')
	else $('.loggedinonly').addClass('noshow')


	if (utype=='landlord') {
				$('#menu_tpn').find('a').attr('href','tpnprerequest.php')
		}
	else if (utype=='rea') {
				$('#menu_tpn').find('a').attr('href','tpnhome.php')
	}

}

function helptext(forwhat) {

	$("#helpdisplay").html('<img src=rpspinbig.gif').show()
	var tourl
	if (forwhat=="fielddescriptions") tourl="ajq_fielddesc.php"
	else tourl="ajq_helptext.php"

		$.ajax({
   			type: "POST",
   			url: tourl,
 			data: "topic="+forwhat,
			dataType: "json",
   			success: function(jr){
				logthis ("fetched field desc")
				$('#helpdisplay').html(jr.respz.html)
				.prepend('<div id="closehelp" style="float:right"><img src="buttons/close.png" alt="close"></div>')
				.show()
				$('#closehelp').unbind().click(function(){$('#helpdisplay').html('')})
					.addClass('clickable')
   			}
 		});
}

function getmyhistory() {
		$.ajax({
   			type: "POST",
   			url: 'ajq_getmyhistory.php',
// 			data: "topic="+forwhat,
			dataType: "json",
   			success: function(jr){
				$('#selectarea').html(jr.respz.html).show()
				$('.historyclose').unbind().click(function(){
						$('.historybox').remove()
						$(this).remove()
						})
					.addClass('clickable')
				$('.gotoitem').each(function(){
						$(this).unbind()
								.click(function(){
								DoenAjax_showmaxi('listing','record_id',
									'resultarea',
									$(this).attr('recno'),'no','no')
						setback('closemaxi')
	// final param=recno
//TODO setback => close
							})
						})
				$('.historydelete').each(function(){
						$(this).unbind()
								.click(function(){
								DoenAjax_deletebasketitem($(this).attr('hrecid'),getmyhistory)
							})
						})
   			}
 		});
}

function DoenAjax_deletebasketitem(hrecid,callback) {

		$.ajax({
   			type: "POST",
   			url: 'ajq_delmyhistory.php',
 			data: "record_id="+hrecid,
			dataType: "json",
   			success: function(jr){

				callback()

   			}
 		});
}

function contactowner(obj,record_id,xpos,ypos) {  //called ia from jquery_rentsa DoenAjax_showmaxi

	var poststr="record_id="+record_id
		$.ajax({
   			type: "POST",
   			url: "ajq_getmailownerform.php",
			data: poststr,
			dataType: "json",
   			success: function(jr){
	 			$(obj).after(jr.respz.html)
				if ($.browser.msie ) {
								$('#chartarea').hide()
								$('#footer').hide()
				}
				window.scrollBy(0,200)
				$('#mf_submit').unbind()
					.click(function(){
							submitcontactowner( $(this).parents('form'),'mf_feedback')
							return false
							})
				$('.closebox').unbind().click(
						function(){
							$('#contactowner_form').remove()
							if ($.browser.msie ) {
								$('#chartarea').show()
								$('#footer').show()
							}

				})

				$('#gotologin').unbind().click(function() {
						$('.contactowner_form').remove()
						DoenAjaxLoginbox('expanded')
					})
				.addClass('clickable')

				$('#contactowner_form').css('top',0)
   			}
 		});
}

function reptun(obj,record_id,xpos,ypos) {  //called ia from jquery_rentsa DoenAjax_showmaxi

	var poststr="submit=yes&record_id="+record_id
		$.ajax({
   			type: "POST",
   			url: "ajq_getreptunform.php",
			data: poststr,
			dataType: "json",
   			success: function(jr){
	 			$(obj).after(jr.respz.html)
				if ($.browser.msie ) {
								$('#chartarea').hide()
								$('#footer').hide()
				}

				window.scrollBy(0,400)

				$('#mf_submit').unbind()
					.click(function(){
							submitreptun( $(this).parents('form'),'mf_feedback')
							return false
							})
				$('.closebox').unbind().click(
						function(){
							$('#reptun_formcontainer').remove()
							if ($.browser.msie ) {
								$('#chartarea').show()
								$('#footer').show()
							}
				})

				$('#gotologin').unbind().click(function() {
						$('.contactowner_form').remove()
						DoenAjaxLoginbox('expanded')
					})
				.addClass('clickable')

				$('#contactowner_form').css('top',0)
   			}
 		});
}


function submitcontactowner(formobj,targetdiv) {
 	var poststr=$(formobj).formSerialize()+"&targetdiv=mf_feedback"
 	//TODO does ajq_saveform.php need a table var?
 	if (validateform(formobj)==0) {  //counts no of erroneous fields

		$('#'+targetdiv).html('<img id="spinner" src=rpspinbig.gif>')
		$.ajax({
   			type: "POST",
   			url: "ajq_mailcontactowner.php",
			data: poststr,
			dataType: "json",
   			success: function(jr){
				$('#'+jr.respz.targetdiv).appendTo(jr.respz.html)
				$('#mf_submit').hide().next('.closebox').children('img').attr('src','buttons/closesend.png')

				window.setTimeout('killspinner()',2000)
   			}
 		});
 	}
}

function killspinner() {
	$('#spinner').parent().html('<span class="errormsg">Message sent</span>')
}

function submitreptun(formobj,targetdiv) {
 	var poststr=$(formobj).formSerialize()+"&targetdiv=mf_feedback"
 	//TODO does ajq_saveform.php need a table var?

 	if (validateform(formobj)==0) {  //counts no of erroneous fields
		$('#'+targetdiv).html('<img src=rpspinbig.gif>')
		$.ajax({
   			type: "POST",
   			url: "ajq_reptunac.php",
			data: poststr,
			dataType: "json",
   			success: function(jr){
				$('#'+jr.respz.targetdiv).html(jr.respz.html)
				$('#mf_submit').next('.closebox').html('Close')
   			}
 		});
 	}
}


function mylogo() {
		$.ajax({
   			type: "POST",
   			url: 'ajq_mylogo.php',
 			data: "username_forlogo="+$('#username_forlogo').val(),
			dataType: "json",
   			success: function(jr){
				$('#resultarea').html('<!-- -->')
				$('#resultarea_logo').html(jr.respz.html)
				setClickable_picinstrip_corplogo('shortlist')
				 setClickable_delpic('delpic')  // in jquery_usradm.js
				 // primarypic also set with delpic

   			}
 		});
}

function setClickable_picinstrip_corplogo(anchorclass){ //allow user to delete pics
		$('.'+anchorclass).each(function(j) {
					$(this).unbind("click")
						.click(function(){
							var record_id=$(this).parents('.picholder').attr('record_id')
							var picpath=$(this).attr('src')
							$('.clientlogo')
								.attr('src',picpath)
/*								.width(300)
								.parent().width(300)*/
							}) //click function
						.attr('style','cursor:pointer')
				})
}

function myrecord() {
	DoenAjax_buildinput_for_users ('users','title_id',
										'resultarea',
									  'useloggedon')
	$('.reload').show()
	window.setTimeout('waitforhide()',1000)
/*	$.elementReady('isready', function(){
    	$('.canhide').hide()
	});*/
}

function waitforhide() {
	if ($('#isready').html()=='R') $('.canhide').hide()
	else window.setTimeout('waitforhide()',1000)

// 	logthis($('#isready').html())

}


