$(function() {
	// form validation
	// custom method for validating US phone numbers
	jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
    	phone_number = phone_number.replace(/\s+/g, "");
		return this.optional(element)
			|| phone_number.length > 9 && phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
	}, "Please specify a valid phone number");
	
	var validator = $("form#rentReg").validate({
		//debug: true,
		groups: {
			fullname: "fname lname"
		},
		onkeyup: false,
		rules: {
			fname: "required",
			lname: "required",
			ClientEmail: {
				required: true, email: true, remote: {
					url: "/ajax_handler/ajax_handler.cfm",
					type: "get"
				}
			},
			password: {
				required: true,
				minlength: 4,
				maxlength: 20
			},
			password_conf: {
				required: true,
				minlength: 4,
				maxlength: 20,
				equalTo: "#password"
			},
			telnum: {
				required : true,
				phoneUS : true
			},
			client_type: "required",
			realestatePro: "required",
			agreement: "required",
			IndoorSqFtRent: "digits",
			username: {
				remote: {
					url: "/ajax_handler/ajax_handler.cfm",
					type: "get"
				},
				required: true
			}
		},
		messages: {
			fname: "first name is required",
			lname: "last name is required",
			ClientEmail: {
				required: "required",
				email: "enter a valid email address",
				remote: jQuery.format("{0} is already registered")
			},
			password: {
				required: "password is required",
				minlength: "the minimum is four characters",
				maxlength: "password length cannot exceed 20 characters"
			},
			password_conf: "retype your password",
			telnum: "enter a valid telephone number",
			client_type: "choose a client type",
			realestatePro: "if you are a real estate agent, please visit brokersnyc.com or contact us at 212-220-5469",
			agreement: "you need to agree to the terms of use before you can create an account",
			IndoorSqFtRent: "only digits required",
			username: {
				required: "required",
				remote: jQuery.format("{0} is already registered")
			}
		},
		errorPlacement: function(error, element) {
			if (element.attr("name") == "fname" || element.attr("name") == "lname")
				error.insertAfter("#lname");
			else if ( element.is(":radio") )
				$('#err_tmp').wrap(error);
			else if ( element.is(":checkbox") )
				error.insertAfter( element.next() );
			else
				error.insertAfter( element );
		},
		invalidHandler: function(e, validator) {
			var errors = validator.numberOfInvalids();
			if (errors) {
				var message = 'there are errors on the page';
				$("div.error span").html(message);
				$("div.error").show();
			} else {
				$("div.error").hide();
			}
		},
		submitHandler: function(form) {
			var options = {
				target:		"#step2",
				url:		"/ajax_handler/ajax_handler.cfm",
				type:		"post",
				dataType:	"html",
				success:	function(data, status) { $('#step2').html(data) },
				error:		function(a, status, err) { $('#step2').html('<div class="success_reg"><h3>There was a problem with registration. Please try again later or contact support.</h3><p>Tech info status: '+status+' err: '+err+'</p></div>') }
			};
			$(form).ajaxSubmit(options);
		}
	});
	
	// Hides next/skip on the last step of reg.
	$('#step2 .next,#step2 .skip').css({'visibility' : 'hidden'});
	
	$('.date-pick').datepicker({ dateFormat: 'yy-mm-dd' });
	
	$('#telnum').mask("(999) 999-9999");
	
	// My Profile form validation
	var validator_profile = $('form#profile').validate({
		onkeyup: false,
		rules: {
			clientemail: {
				remote: "/ajax_handler/ajax_handler.cfm",
				required: true
			},
			username: {
				remote: '/ajax_handler/ajax_handler.cfm',
				required: true
			}
		},
		messages: {
			clientemail: {
				remote: jQuery.format("{0} is already registered"),
				required: 'email is reqired'
			},
			username: {
				remote: jQuery.format("{0} is already used"),
				required: 'username is required'
			}
		},
		submitHandler: function() { sendForm(this) }
	});
	
	// Submittal of mymlx forms.
	$('.profile_forms').submit( function() { sendForm(this); return false; } );
	function sendForm(id) {
		var options = {
		  target:	"#msgarea1",
		  url:		"/ajax_handler/ajax_handler.cfm",
		  type:		"post",
		  dataType:	"html",
		  success:	function(data, status) { $('#msgarea1').addClass('success_reg').html('Your information has been successfully updated<br />'+data); },
		  error:	function(a, status, err) { $('#msgarea1').addClass('success_reg').html('An error has occurred while updating information. Please try again later.<br />status:'+status+',cause:'+err); }
		};
		$(id).ajaxSubmit(options);
		return false;
	}
	
	// This is a quick hack to make users choose a customer type, otherwise building preferences/price will remain disabled.
	// Default to 'renter'
	$('input.client_type[value=1],input.client_type[value=2]').click(function() {
		$('tr#maxrentTR').css('display', 'table-row');
		$('tr#maxaskTR').css('display','none');
		$('tr.forbuyers').css('display','none');
	});
	$('input.client_type[value=3]').click(function() {
		$('tr#maxrentTR').css('display','none');
		$('tr#maxaskTR').css('display', 'table-row');
		$('tr.forbuyers').css('display', 'table-row');
	});
	$('input.client_type[value=1]').attr('checked', 'checked').click();
});

$(function() {
	/* Forgotten password */
	$('a#mail_password').click(function() {
		$('div#mail_password').show();
	});
	var o = {
			url:		'/ajax_handler/ajax_handler.cfm',
			error:		function (a, status, err) { $('#msgarea').html(status+', '+err)  },
			success:	function (data, status) { $('#msgarea').html(data) },
			type:		'post',
			target:		'#msgarea'
	}
	$('form#mail_password').submit(function() {
		if ( $('input#clientemail').val() )
			$(this).ajaxSubmit(o);
		else
			$('#msgarea').html('<div class="success_reg">the field is empty</div>');
		return false;
	});
});

$(function() {
	/* mymlx: delete saved search entries */
	var o = {
		url:		'/ajax_handler/ajax_handler.cfm',
		error:		function(a, status, err) { alert('error:'+status+'. '+err) },
		success:	function(data, status) {
			a = data.replace(/\s*/g,"").split(','); for (i in a) { $('tr#'+a[i]).css('display', 'none') } },
		type:		'post',
		dataType:	'text'
	}
	$('form#savedSearch').submit(function() {
		if (confirm('Are you sure you want to delete the selected searches?'))
			$(this).ajaxSubmit(o);
		return false;
	});
	
	/* new search button */
	$('input#new_rent_search').click(function() {
		document.location.href = '/rent';
	});
	$('input#new_sale_search').click(function() {
		document.location.href = '/sale';
	});
});

/*function sendRegForm() {
	var n = $("#rentReg").serialize();
	$.post('/tmp2.cfm',n,function(data,status) {
		$("#msgarea").html(data);
		if ($('#reg1').val() == '1') {
			$('#step1 > .header').hide('fast');
			$('#step1').children('.stepLeft').html("<h3 class='pinktxt'>Thank you for registering with MLX</h3><br /><br /><div><span class='graytxt'><p>You may proceed with the consultation process (click <b>next</b>) in order to better your chances for finding the right place or, alternatively, you may choose to start browsing through our listings.</p><br /><a class='nav' href='http://dev7.mlx.com/rentals'>view listings</a></span></div>");
			$('div#footer').show();
			$.post('/action=mymlx&subaction=validation&type=doLogIn&frame=blank');
			$('div#sighout_loggedin').css({'visibility' : 'visible'});
			$('div#signin_loggedout').css({'visibility' : 'hidden'});
		}
	});
	return false;
}*/

/*function sendForm(formName) {
	$.post(webroot+'?action=mymlx&subaction=myaccount&update=1&frame=blank&use_ga=0',$(formName).serialize(),function(data,status) {
		$("#msgarea").html(data);
	});
	return false;
}*/

/*$(document).ready(function() {
	$('.toggle').each(function () {
		if (!$(this).is('.open-first')) {
			$(this).addClass('closed');
		}
	});
	$('.toggle').prev().each(function () { 
		$(this).html('<a href="#" style="padding:7px 0px 7px 7px; font-size:16px; font-weight:bold;  background:#f8f8f8; display:block; width:450px; border-bottom:1px solid #fff; float:left; clear:both;" class="toggleLink">'+$(this).html()+'</a>');
		$('.closed').hide();
	});
	$('a.toggleLink').click(function() {
		$('.toggle').each(function () {	
			if($(this).is('.open') || $(this).is('.open-first')) {
				$(this).removeClass('open')
				$(this).addClass('closed')
			}
		});
		$(this).parent().next('.toggle').addClass('open')
		$(this).parent().next('.toggle').removeClass('closed')
		$('.open').show('slow');$('.closed').hide('slow');
		return false;
	});
});*/