$(document).ready(function(){
	$("#jqfeedback").html('[:)]')
	$("#requsername").blur(function(){ DoenAjaxRequestUsernameSignup('savinglabel') })
//	$("#email2").hide()
	$("#newemail").blur(function(){ compare_emails() })
		.click(function(){ $("#newemailfeedback").html('') })
	
	var usn=$('#getto').children('input[@name=getto_usn]').val()
	if (usn!=undefined) {$('#incsearcharea').show()
					DoenAjaxLoginbox('expanded')
					}
	$('#dologon').click(function() { DoenAjaxLoginbox('expanded') })
	.addClass('clickable')

	$('#proceedconfirmed').click(function() { window.location="index.php" })
	.addClass('clickable')

	var passkey=$('#getto_passkey').val()
	if (passkey!=undefined) $('#incsearcharea').show()
//	$('#submitsignupform').hide()

	$('#submitsignupform') // for editing
					.unbind()
					.click(function() { 
						//alert('posting')
						DoenAjaxSubmitEditing ()
						})


	setuptandc()
	
	checkcorrmail()  // correspondence email, as opposed to username email

	$('#emailaltx').change(function() {
		 checkcorrmail() 
	})

	$('#emailaltx').blur(function() {
		 checkcorrmail() 
	})

//	if ($.browser.msie) {

		$('#ut1').click(function() { 
			$('#usertype').children('input[@name=utype]').val('tenant') 
			getusertypesubform(this)
		})
		$('#ut2').click(function() { 
			$('#usertype').children('input[@name=utype]').val('landlord')
			getusertypesubform(this)   
		})
		$('#ut3').click(function() { 
			$('#usertype').children('input[@name=utype]').val('rea') 
			getusertypesubform(this)   
		})
		$('#ut4').click(function() { 
			$('#usertype').children('input[@name=utype]').val('investor') 
			getusertypesubform(this)   
		})

/*	}
	else {
		$('#usertype').children('input[@name=utype]').change(function() {*/
//			getusertypesubform(this) 
/*			$('#usertype').children('.sulbl2').addClass('dim')*/
//		})
//	}

	// link event handler for  button on text fragment area search
	$("#subformdiv").find('.setclick').click(function(){
			DoenAjax_setupsearch_areafromfrag('areaselector','nil') 
	})

	$('#searchtext').bind('keypress', function(event) {
			var code=event.charCode || event.keyCode;
			if(code == 13) {
			DoenAjax_setupsearch_areafromfrag('areaselector','nil') 
			}
		})

// for existing users, not new users, form not painted in sections
	setupcalendar()



// NUMERIC.js must be included.. or this will fail
		$('.numbersonly').numeric()

		$('.warning').remove()
});
//============================================
function setuptandc() {
	$('#accepttandc').unbind()
	.change(function(){ if(this.checked) $("#submitsignupform").show()
						else $("#submitsignupform").hide()
						})
	.click(function(){ if(this.checked) $("#submitsignupform").show()
						else $("#submitsignupform").hide()
						})
}
//============================================
function checkcorrmail() {
	var altmail=$('#emailaltx').val()
	if (altmail=='') {
		$('#coralt').hide()
		$('#corresp').show()
	}
	else {
		$('#coralt').show()
		$('#corresp').hide()
	}

}
//============================================
function getusertypesubform(obj){
	// gets selected elements from universe of form elements
	// and if needed, area fragment text search box
	//$(obj)./*children('.sulbl2').*/addClass('dim')
	var usertype=$(obj).val()
	var poststr= "&usertype=" + usertype
	$("#subformdiv").html("<img src=\"rpspinbig.gif\">")
			$.ajax({
   			type: "POST",
   			url: "ajq_getgeneralsignupsubform.php",
			data: poststr,
			dataType: "json",
   			success: function(jr){
   				$("#subformdiv").html(jr.respz.form)
				window.scrollBy(0,400)
					// clear out next stage, maybe user retracted
					$('#nextstage').html('')
		
		

					// enable a control to bring up the next stage when clicked	
					$('#who1').click(function() { 
						$('#usertype').children('input[@name=whomanages]').val('own') 
						DoenAjax_putareainput(usertype,'own')
//						shownextstage(usertype)
					})
					$('#who2').click(function() { 
						$('#usertype').children('input[@name=whomanages]').val('rea') 
						DoenAjax_putareainput(usertype,'rea')
//						shownextstage(usertype) 
					})

					$('#cmeproceed').click(function() { 
						if (validatebudget_ptt() )	DoenAjax_putareainput('tenant')
					})
					.addClass('clickable')

					$('#whomanproceed').click(function() { 
						DoenAjax_putareainput('landlord')
					})
					.addClass('clickable')

					// entering in field, clicking on proceed for rea company name ...
					$('#conameproceed').click(function() { 
						DoenAjax_putareainput('rea')
						$(this).remove()
					})
					.addClass('clickable')

					$('#company').bind('keypress', function(event) {
    					var code=event.charCode || event.keyCode;
    					if(code == 13) {
							DoenAjax_putareainput('rea')
							$('#conameproceed').remove()
    					}
					})

					$('input[@name=budgetfrom]').add('input[@name=budgetto]').numeric()
// investor goes directly to next step

					if (jr.respz.usertype=='investor') {
//						alert()
						DoenAjax_putareainput(usertype,'nil')
					}
					
					setupcalendar()

   			}
 		});
}
//============================================
function DoenAjax_putareainput(usertype,whomanages) { 
	$('#putareainputhere').html('<img src=rpspinbig.gif alt="Loading">')
	var searchtext=$('#textfrag').find('input[@name=searchtext]').val()
//alert(searchtext)
	var poststr="usertype="+usertype+"&whomanages="+whomanages
		$.ajax({
   			type: "POST",
   			url: "ajq_getareainput.php",
			data: poststr,
			dataType: "json",
   			success: function(jr){
				$('#putareainputhere').html(jr.respz.areaselector);
				window.scrollBy(0,600)

				$("#subformdiv").find('.setclick').click(function(){
						DoenAjax_setupsearch_areafromfrag('areaselector',usertype) 
				})

				$('#searchtext').bind('keypress', function(event) {
    					var code=event.charCode || event.keyCode;
    					if(code == 13) {
						DoenAjax_setupsearch_areafromfrag('areaselector',usertype) 
    					}
					})

			}
		})
}
//============================================
function DoenAjax_setupsearch_areafromfrag(targetdiv,usertype) {
    // creates select control from text fragment
    // uses input from user to find matching areas and put these in 
    // select control.  Also activated if searchtext is posted and inserted by php into 
    // element.id "searchtext"
    // since more than one selector can be put onto a page, stick some id onto the generic id
    // use targetdiv for this (ga1,ga2,ga3 in this case)
    // making id like:area_id_selectorga1  area_id_selectorga2 ...
    if (usertype != 'tenant') {
        $('#'+targetdiv).html('<img src=rpspinbig.gif alt="Loading">')
    } else {
        $("#area_id_selector_jumpOver_select1").removeOption(/./);
    }
    var searchtext=$('#textfrag').find('input[@name=searchtext]').val()
    var poststr="targetdiv="+targetdiv+"&searchtext="+searchtext+"&usertype="+usertype
        $.ajax({
            type: "POST",
            url: "ajq_stpsrch_frmfrg_bnr.php",
            data: poststr,
            dataType: "json",
            success: function(jr){
                if (usertype != 'tenant') {

                    $('#'+jr.respz.targetdiv).html(jr.respz.html);
                } else {
                    // if tenant, then just update the existing jumpover box
                    $('#area_id_selector_jumpOver_select1').addOption(jr.respz.html);
                }
                    window.scrollBy(0,600)

                    $('#'+jr.respz.targetdiv)
                        .find('.area_id_selector').unbind()
                        .click(function(){   // only show add button when area is selected
                                var areaname=$('#'+jr.respz.targetdiv).find('select option:selected').text()
                                $('#areaname').html(areaname)
                                $('#areapref').val( $('#area_id_selector').val())
                        if(document.getElementById("actionoption")){
                        }else{
                        // enable a control to bring up the next stage when clicked
                         shownextstage(usertype)
                        }

                            })
            }
        });
}
//============================================
function shownextstage(usertype) {
	if (usertype=='nil') return // for non ajax
	var poststr='usertype='+usertype
	$.ajax({
   			type: "POST",
   			url: "ajq_getsubfinstage.php",
			data: poststr,
			dataType: "json",
   			success: function(jr){
				$('#nextstage').html(jr.respz.html).show()
				$('#submitsignupform')
//					.hide()
					.unbind()
					.click(function() { 
						//alert('posting')
						DoenAjaxSubmitNewUser ()
						})

		$('body').bind('keypress', function(event) {
    					var code=event.charCode || event.keyCode;
    					if(code == 13) {
							return false
    					}
					})

				setuptandc()
				window.scrollBy(0,400)
			}
	})
		
}
//============================================

function DoenAjaxRequestUsernameSignup(savinglabel){
	// checks email for validity and availability
	var usn=$("#requsername").val()
	if (usn=='') return
	var poststr= encodeURI(savinglabel) + "&username=" + encodeURI(usn)
	$("#savinglabel").html("<img src=\"rpspinbig.gif\">")
			$.ajax({
   			type: "POST",
   			url: "ajq_requsersignup.php",
			data: poststr,
			dataType: "json",
   			success: function(jr){
//   				if (jr.respz.count==0) $("#email2").show()
   				$("#savinglabel").html(jr.respz.html)
				$("#isemailvalid").val(jr.respz.isemailvalid)
   			}
 		});
}
//============================================

function	DoenAjaxSubmitEditing () {
	$('form[@name=signupform]')[0].submit()
}
//============================================

function validatebudget_ptt() {
	$('.failvalidate').removeClass('failvalidate')

	if ($('input[@name=budgetfrom]').val()!=undefined) {
		var bfrom=$('input[@name=budgetfrom]').val()
		if (bfrom=='') {
			$('input[@name=budgetfrom]')[0].focus()
		   $('input[@name=budgetfrom]').addClass('failvalidate')
			alert('Please enter a minimum amount for budget')
			return false
		}
	}


	if ($('input[@name=budgetto]').val()!=undefined) {
		var bto=$('input[@name=budgetto]').val()
		if (bto=='') {
			$('input[@name=budgetto]')[0].focus()
		   $('input[@name=budgetto]').addClass('failvalidate')
			alert('Please enter a maximum amount for budget')
			return false
		}
	}

//parseInt($('.mq').css('margin-left'),10)
	if (parseInt(bto)<=parseInt(bfrom)) {
		alert('Please ensure that Budget from is less than Budget to')
		$('input[@name=budgetto]')[0].focus()
		$('input[@name=budgetto]').addClass('failvalidate')
		return false
	}

	if ($('select[@name=propertytype]').val()!=undefined) {
		var ptt=$('select[@name=propertytype]').val()
		if (ptt=='empty') {
			$('select[@name=propertytype]')[0].focus()
			$('select[@name=propertytype]').addClass('failvalidate')
			alert('Please select a property type')
			return false
		}
	}


	var rentduration=$('#rentdurationrentduration').val()
	var furnishing=$('#furnishingfurnishing').val()
	var daterentfrom=$('#daterentfrom').val()


	if (rentduration!=undefined) {

		if (rentduration=='empty') {
			alert ('Please choose a rent duration')
			$('#rentdurationrentduration').addClass('failvalidate')
			return false
		}
	
		if (furnishing=='empty') {
			alert ('Please choose a furnishing option')
			$('#furnishingfurnishing').addClass('failvalidate')
			return false
		}

		if (daterentfrom=='') {
			alert ('Please choose a start date')
			$('#daterentfrom').addClass('failvalidate')
			return false
		}
	}
	return true

}
// --------------------------------------
function DoenAjaxSubmitNewUser () {

	$('.failvalidate').removeClass('failvalidate')

	var fullname=$('#fullname').val()
	var requsername=$('#requsername').val()
	var newemail=$('#newemail').val()
	

	if (fullname=='') {
		alert('Please enter your Full Name')
		$('#fullname')[0].focus()
		return false
	}


	if (requsername=='') {
		alert('Please enter your email address as username')
		$('#requsername')[0].focus()
		return false
	}

	if (newemail=='') {
		alert('Please retype your email address to allow a double check')
		$("#newemail")[0].focus()
		return false
	}
	
	if (!validatebudget_ptt()) return false
	

	if ($("#requsername").attr('required')=='req') {
		if ($("#requsername").val() != $("#newemail").val()) {
			alert("Emails don\'t match\nPlease re-enter your email address to allow a double check")
			$("#newemail")[0].focus()
		return false
		}
	}

	var password= $("#password").val()
	if ($("#password").attr('required')=='req') {
		if (password =="") {
			alert("Please enter a password")
			$("#password")[0].focus()
		return false
		}	
	}
	else {
	}

	var privateanswer=$("#privateanswer").val()
	var privatequestion=$("#privatequestion").val()
	if ((privateanswer =="") || (privatequestion =="")){
		alert("Please enter a private question\nas well as the answer to this question")
		$("#privatequestion")[0].focus()
		return false
	}

	var showemail=$("#showemail").val()

	if ((showemail =="empty") || (showemail =="")){
		alert("Please select whether your email should be displayed\nwith your listing")
		$("#showemail")[0].focus()
		return false
	}


	

// REL 2
	$('form[@name=signupform]')[0].submit()
	return

//	var usercategory=$("#usercategory").val()

/*
	var usercategory=[$("[@name=usercategory]:checked").val()]


	var poststr = "fullname=" + encodeURI(fullname) + "&requsername="+encodeURI(requsername) + "&newemail="+encodeURI(newemail)+"&usercategory="+usercategory+"&password="+encodeURI(password)+"&privatequestion="+encodeURI(privatequestion)+"&privateanswer="+encodeURI(privateanswer)+"&showemail="+encodeURI(showemail)+"&updating="+$('#updating').val()

	$.ajax({
   			type: "POST",
   			url: "ajq_usersignup.php",
			data: poststr,
			dataType: "json",
   			success: function(jr){
   				$("#useraction").html(jr.respz.html)
				window.scrollBy(0,400)
				$('#continuebutton').unbind()
						.click(function() { 
							window.location="index.php"
						  $("#useraction").html(jr.respz.submitbutton) })
   				}
	});
*/
}
