// field labelling and clearing on hover
var fieldLabels = {
	addInlineLabel: function(elt) {
		if (elt.value == '') {
			elt.value = elt.defaultValue;
		}
	},
	removeInlineLabel: function(elt) {
		if (elt.value == elt.defaultValue) {
			elt.value = '';
		}
	},
	init: function() {

		this.forms = $('form');
		if (!this.forms) return;
		
		// events
		this.forms.each(function(){
			this.controls = $(this).find('.inline_labelled');
			this.controls.blur(function(){
				fieldLabels.addInlineLabel(this);
			}).focus(function(){
				fieldLabels.removeInlineLabel(this);
			});
		});
		this.forms.submit(function(){
			this.controls.each(function(){
				fieldLabels.removeInlineLabel(this);
			});
		});
		
	}
}

// visibility of send email form portions
var sendEmailForm = {
	pickMethod: function(toggle) {
		return {
			open: (toggle) ? 'slideDown' : 'show',
			close: (toggle) ? 'slideUp' : 'hide'
		};
	},
	goalCbsChecked: function() {
		return (sendEmailForm.goalCbs.is(':checked'));
	},
	inEmailForm: function(evt) {
		if (!evt) return false;
		return ($(evt.target).closest('#sendemailform').length)
	},
	setActive: function(evt,animated) {
		var methods = sendEmailForm.pickMethod(!!(evt || animated));
		if (sendEmailForm.openCondition(evt)) {
			sendEmailForm.flashOnPage.css('visibility','hidden');
			sendEmailForm.otherControls[methods.open]();
		} else {
			sendEmailForm.otherControls[methods.close](null, function(){
				sendEmailForm.flashOnPage.css('visibility','visible');
			});
		}
	},
	setGoalsDisplay: function(animated) {
		var methods = this.pickMethod(animated);
		this.goalCbs.each(function(index, elt){
			if (elt.checked) {
				$(sendEmailForm.goalFields[index])[methods.open]();
			} else {
				$(sendEmailForm.goalFields[index])[methods.close]();
			}
		});
	},
	setAgentsDisplay: function(animated) {
		var methods = this.pickMethod(animated);
		if (this.agentsRadios.is('#chooseagents:checked')) {
			this.agentsField[methods.open]();
		} else {
			this.agentsField[methods.close]();
		};
	},
	init: function() {
		
		// checks
		this.sendEmailForm = $('#sendemailform');
		if (!this.sendEmailForm.length) return;
		this.formType = this.sendEmailForm.find('form')[0].id;
		
		// BOTH FORMS
		
		// variables
		this.agentsRadios = this.sendEmailForm.find('#fieldagents input:radio');
		this.agentsField = this.sendEmailForm.find('#field_sendlistagents');
		this.flashOnPage = $('object, embed').parent();
		
		// functions
		this.setAgentsDisplay(false);
		
		// validation
		$('*[validate]').parent().append('<span class="asterisk">*</span>');
		$.metadata.setType("attr", "validate");
		this.coreValidationOptions = {
			messages: {
				name: 'your name',
				email: {
					required: 'your email address',
					email: 'a valid email address'
				},
				phone: {
					required: 'your phone number',
					phoneUK: 'a valid phone number'
				},
				sendlistagents: 'at least one location agent to send to',
				terms: 'your agreement to the terms and conditions'
			},
			highlight: function(element, errorClass, validClass) {
				$(element).parent().addClass(errorClass).removeClass(validClass);
			},
			unhighlight: function(element, errorClass, validClass) {
				$(element).parent().removeClass(errorClass).addClass(validClass);
			},
			errorContainer: '#validationMessage',
			errorLabelContainer: '#validationMessage ul',
			wrapper: 'li',
			invalidHandler: function(event,validator){
				validator.currentForm.controls.each(function(){
					fieldLabels.addInlineLabel(this);
				});
			},
			focusInvalid: false
		}
		
		// events
		this.agentsRadios.click(function(){
			sendEmailForm.setAgentsDisplay(true);
		});
		
		switch (this.formType) {
			
			// ESTATE AGENTS FORM
			case 'estateemail':
		
				// variables
				this.submits = this.sendEmailForm.find('button[type="submit"]');
				this.goalCbs = this.sendEmailForm.find('#field1 input:checkbox');
				this.goalFields = this.sendEmailForm.find('#fieldsell, #fieldbuy, #fieldlet, #fieldrent');
				this.otherControls = this.sendEmailForm.find('#fieldinfo, #fieldagents, #fieldterms, #validation');
				this.openCondition = this.goalCbsChecked;
				
				// functions
				this.setActive(null,false);
				this.setGoalsDisplay(false);
		
				// validation
				var validator = $('#estateemail').validate($.extend(true, this.coreValidationOptions, {
					messages: {
						goal: 'whether you wish to sell, buy, let and/or rent (at least one)',
						sell_bedrooms: 'the number of bedrooms in the property you wish to sell',
						sell_type: 'the type of property you wish to sell',
						let_bedrooms: 'the number of bedrooms in the property you wish to let',
						let_type: 'the type of property you wish to let',
						let_minprice: 'the minimum rent you would accept',
						buy_bedrooms: 'the number of bedrooms in the property you wish to buy',
						buy_type: 'the type of property you wish to buy',
						buy_maxprice: {
							required: 'the maximum price you would pay',
							greaterThanOther: 'a maximum purchase price greater than your minimum'
						},
						buy_minprice: {
							required: 'the minimum price you would pay'
						},
						rent_bedrooms: 'the number of bedrooms in the property you wish to rent',
						rent_type: 'the type of property you wish to rent',
						rent_maxprice: 'the maximum rent you would pay'
					}
				}));
				
				$('#buy_minprice').change(function(){
					validator.element($('#buy_maxprice').get(0));
				});
				
				// events
				this.goalCbs.click(function(){
					sendEmailForm.setActive(null,true);
					sendEmailForm.setGoalsDisplay(true);
				});
			
			break;
            // VALUATION FORM             case 'valuationemail':
                // variables                this.otherControls = this.sendEmailForm.find('#fieldvaluation, #fieldinfo, #fieldagents, #fieldterms, #validation');                this.openCondition = this.inEmailForm;
                // functions                this.setActive(null, false);
                // validation                $('#valuationemail').validate($.extend(true, this.coreValidationOptions, {                    messages: {                                value_bedrooms: 'the number of bedrooms in the property you wish valued',                                value_type: 'the type of property you wish valued'                    }                }));

                // events
                $(document).click(this.setActive);
                $('#valuationemail').find('input, select, textarea').focus(this.setActive);

            break;  
                          				
			// MORTGAGE AGENTS FORM
			case 'mortgageemail':

				// variables
				this.otherControls = this.sendEmailForm.find('#fieldproperty, #fieldhistory, #fieldagents, #fieldterms, #validation');
				this.openCondition = this.inEmailForm;
				
				// functions
				this.setActive(null,false);
	
				// validation
				$('#mortgageemail').validate($.extend(true, this.coreValidationOptions, {
					messages: {
						property_value: 'the value of your property',
						mortgage_amount: 'the mortgage amount',
						mortgage_term: 'the mortgage term',
						repayment_type: 'the repayment term',
						history_details: 'the details of your credit history'
					}
				}));
				
				// events
				$(document).click(this.setActive);
				$('#mortgageemail').find('input, select, textarea').focus(this.setActive);
				
			break;
			
		}
		
	}
}

// valuation form
var valuationForm = {
	init: function() {
		
		// checks
		this.form = $('#valuationform');
		if (!this.form.length) return;

		// validation
		$('*[validate]').parent().append('<span class="asterisk">*</span>');
		$.metadata.setType("attr", "validate");
		this.form.validate({
			groups: {
				postcode: 'postcode1 postcode2'
			},
			messages: {
				name: 'your name',
				email: {
					required: 'your email address',
					email: 'a valid email address'
				},
				phone: {
					required: 'your phone number',
					phoneUK: 'a valid phone number'
				},
				postcode1: 'your postcode',
				postcode2: 'your postcode',
				typeofproperty: 'the type of property',
				nobedrooms: 'the number of bedrooms',
				nobathrooms: 'the number of bathrooms',
				noreceptions: 'the number of reception rooms',
				garden: 'whether or not it has a garden',
				garage: 'whether or not it has a garage',
				parking: 'the number of parking spaces',
				heating: 'whether or not it has central heating',
				condition: 'the property\'s condition',
				propertyage: 'the age of the property',
				reason: 'your reason for wanting the valuation'
			},
			highlight: function(element, errorClass, validClass) {
				$(element).parent().addClass(errorClass).removeClass(validClass);
			},
			unhighlight: function(element, errorClass, validClass) {
				$(element).parent().removeClass(errorClass).addClass(validClass);
			},
			errorContainer: '#validationMessage',
			errorLabelContainer: '#validationMessage ul',
			wrapper: 'li',
			invalidHandler: function(event,validator){
				validator.currentForm.controls.each(function(){
					fieldLabels.addInlineLabel(this);
				});
			},
			focusInvalid: false
		});
		
	}
}

var postcodeSearchForm = {
	init: function() {
		
		// checks
		this.form = $('#price_search_form');
		if (!this.form.length) return;

		// validation
		$.metadata.setType("attr", "validate");
		this.form.validate({
			messages: {
				locality: 'Please enter a postcode.'
			},
			highlight: function(element, errorClass, validClass) {
				$(element).parent().addClass(errorClass).removeClass(validClass);
			},
			unhighlight: function(element, errorClass, validClass) {
				$(element).parent().removeClass(errorClass).addClass(validClass);
			},
			errorLabelContainer: '#validationMessage',
			invalidHandler: function(event,validator){
				validator.currentForm.controls.each(function(){
					fieldLabels.addInlineLabel(this);
				});
			},
			focusInvalid: false
		});
	}
}

// apply class names on condition (branches list)
var expandList = {
	shouldExpand: function() {
		return (this.list.find('a').length > 20);
	},
	init: function() {
		
		this.list = $('#branch-list');
		
		if (!this.list) return;
		if (!this.shouldExpand()) return;
		
		this.container = $('#agentbranches');
		this.showLink = $('#show_full_list a');
		
		this.container.addClass('agentbranches_partial');
		this.showLink.click(function(){
			expandList.container.removeClass('agentbranches_partial');
			return false;
		})
		
	}
	
}

// ie6 hover state
var hovers = {
	matchPatterns: ['#locations_list li'],
	init: function() {
		for (var i=0;i<this.matchPatterns.length;i++) {
			$(this.matchPatterns[i]).hover(function(){
				$(this).addClass('hover');
			},function(){
				$(this).removeClass('hover');
			});
		}
	}
}

// property table
var propertyTables = {
	init: function() {
		// elements
		this.container = $('#price_tables');
		// this.tables = this.container.find('table');
		this.tabs = this.container.find('h2 a');
		this.showNumbers = this.container.find('#numberofsales a')
		
		// events
		this.tabs.click(function(){
			propertyTables.container.removeClass('byprice bytype').addClass(this.hash.substr(1));
			return false;
		});
		this.showNumbers.click(function(){
			if (this.innerHTML.indexOf('show') > 0) {
				this.innerHTML = this.innerHTML.replace('show','hide');
			} else {
				this.innerHTML = this.innerHTML.replace('hide','show');
			}
			propertyTables.container.toggleClass('numbers_shown');
			return false;
		});
		this.tabs.first().click();
	}
}

var presentationalMarkup = {
	markup: '<div class="extra extra_t"></div><div class="extra extra_l"></div><div class="extra extra_r"></div><div class="extra extra_b"></div>',
	elements: ['#valuationform'],
	instances: [],
	init: function() {
		
		if (Modernizr.boxshadow) return;
		for (var i=0;i<this.elements.length;i++) {
			var inst = {};
			inst.element = $(this.elements[i]);
			if (!inst.element.length) return;
			inst.element.append(this.markup);
			this.instances.push(inst);
		}	
		
	}
}

// initiate
$(document).ready(function() {
	fieldLabels.init();
	sendEmailForm.init();
	expandList.init();
	hovers.init();
	propertyTables.init();
	valuationForm.init();
	postcodeSearchForm.init();
	presentationalMarkup.init();
});

