dojo.ready(
	function() {
		if (dojo.byId('valuation_step1')) {
			var propertyType = dojo.byId('property-type').value;
			var propertyStyle = dojo.byId('property-style').value;

			// hide some fields/questions initially
			if (propertyType) {
				if (propertyType == 'house' || propertyType == 'bungalow' || propertyType == 'townhouse') {
					dojo.style('property-style_row', 'display', 'block');
					showUnusualFeatures('house');
				} else if (propertyType == 'studio' || propertyType == 'flat') {
					dojo.style('property-style_row', 'display', 'none');
					dojo.style('extension_row', 'display', 'none');
					showUnusualFeatures('flat');
				}
			}

			if (!dojo.byId('property-garage-1').checked) {
				dojo.style('property-garageSize_row', 'display', 'none');
			}
			if (!dojo.byId('property-garden-1').checked) {
				dojo.style('property-largeGarden_row', 'display', 'none');
			}
			if (!dojo.byId('property-garden-0').checked) {
				dojo.style('property-communalGarden_row', 'display', 'none');
			}

			var addressFilledIn = (dojo.byId('address-address1').value != '' || dojo.byId('address-county').value != '');
			if (!postcodeAnywhere || addressFilledIn) {
				dojo.query('.addressEntry').style('display', 'block');
			} else {
				dojo.query('.addressEntry').style('display', 'none');
			}

			if (!postcodeAnywhere) {
				dojo.style('address_lookup', 'display', 'none');
				dojo.style('address_manual_entry', 'display', 'none');
			}


			dojo.connect(dojo.byId('property-type'), 'onchange', function() {
				var propertyType = dojo.byId('property-type').value;

				// unusual features
				if (propertyType == 'studio' || propertyType == 'flat') {
					showUnusualFeatures('flat');
					dojo.style('property-style_row', 'display', 'none');
					dojo.style('extension_row', 'display', 'none');

				} else if (propertyType == 'house' || propertyType == 'bungalow' || propertyType == 'townhouse') {
					showUnusualFeatures('house');
					dojo.style('property-style_row', 'display', 'block');
					dojo.style('extension_row', 'display', 'block');
				} else {
					hideUnusualFeatures();
					dojo.style('property-style_row', 'display', 'none');
					dojo.style('extension_row', 'display', 'none');
				}

				// rooms
				if (propertyType == 'studio') {
					dojo.style('property-bedrooms_row', 'display', 'none');
					dojo.style('property-bathrooms_row', 'display', 'none');
					dojo.style('property-receptionRooms_row', 'display', 'none');

				} else {
					dojo.style('property-bedrooms_row', 'display', 'block');
					dojo.style('property-bathrooms_row', 'display', 'block');
					dojo.style('property-receptionRooms_row', 'display', 'block');
				}
			});

			dojo.connect(dojo.byId('property-garden-1'), 'onclick', toggleGardenOptions);
			dojo.connect(dojo.byId('property-garden-0'), 'onclick', toggleGardenOptions);

			dojo.connect(dojo.byId('property-garage-1'), 'onclick', toggleGarageOptions);
			dojo.connect(dojo.byId('property-garage-0'), 'onclick', toggleGarageOptions);

			dojo.connect(dojo.byId('address_lookup'), 'onclick', addressSearch);

			// catch enter key in postcode box
			dojo.connect(dojo.byId('property_postcode'), 'onkeydown', function(event){
				if (event.keyCode == dojo.keys.ENTER) {
					addressSearch();

					dojo.stopEvent(event);
				}
			});

			dojo.connect(dojo.byId('address_selector'), 'onchange', function() {
	        	var selectedAddress = dojo.byId('address_selector').options[dojo.byId('address_selector').selectedIndex];

	        	dojo.style('address_selector_spinner', 'display', 'inline');

	        	dojo.xhrGet({
				    url:"/valuation/postcode-lookup/?addressID=" + selectedAddress.value,
				    handleAs:"json",
				    timeout: 4000,
				    load: function(data){
	        			dojo.byId('address-address1').value = data['Line1'];
	        			if (typeof data['Line2'] == 'string') {
	        				dojo.byId('address-address2').value = data['Line2'];
	        			}
	        			if (typeof data['Line3'] == 'string') {
	        				dojo.byId('address-address3').value = data['Line3'];
	        			}
	        			if (typeof data['PostTown'] == 'string') {
	        				dojo.byId('address-city').value = data['PostTown'];
	        			}
	        			if (typeof data['County'] == 'string') {
	        				dojo.byId('address-county').value = data['County'];
	        			}
	        			if (typeof data['Postcode'] == 'string') {
	        				dojo.byId('address-postcode').value = data['Postcode'];
	        			}
	        			showAddressFields();
	        			dojo.style('address_selector_row', 'display', 'none');
	        			dojo.style('address_selector_spinner', 'display', 'none');
	        		},
	        		error: addressSearchError
	        	});
	        });
		}
	}
);

dojo.ready(
	function() {
		dojo.query(".content .collapsible").forEach(
			function(item, index, array){
				if (dojo.hasClass(item.id, 'collapsed')) {
					contentID = item.id + '_content';
					dojo.style(contentID, 'display', 'none');
				}

				dojo.connect(item, 'onclick', function(item) {
					headingID = item.target.id;
					contentID = headingID + '_content';
					dojo.toggleClass(contentID, 'collapsed')
					if (dojo.style(contentID, 'display') == 'block') {
						dojo.style(contentID, 'display', 'none');
						dojo.addClass(headingID, 'collapsed');
					} else {
						dojo.style(contentID, 'display', 'block');
						dojo.removeClass(headingID, 'collapsed');
					}
				});
			}
		);
	}
);


dojo.ready(
	function () {
		if (dojo.byId('valuationFeedbackExpected_row')) {
			dojo.style('valuationFeedbackExpected_row', 'display', 'none');
		}

		dojo.query('#valuationFeedbackAccuracy_row input[type=radio]').forEach(
			function(item, index, array) {
				dojo.connect(item, 'onclick', toggleFeedbackExpected);
			}
		);
	}
);


dojo.ready(
		function() {
			dojo.query("#navigation a").forEach(
				function(item, index, array){
					dojo.connect(item, 'onmouseover', function(item) {
						nav_id = item.target.id;
						subnav_id = nav_id.replace('nav_', 'subnav_');

						if (dojo.byId(subnav_id)) {
							dojo.style(subnav_id, 'display', 'block');
							dojo.style(subnav_id, 'left', item.target.offsetLeft + 'px');
							dojo.addClass(nav_id, 'highlighted');
						}
					});

					dojo.connect(item, 'onmouseout', function(item) {
						nav_id = item.target.id;
						subnav_id = nav_id.replace('nav_', 'subnav_');

						if (dojo.byId(subnav_id)) {
							dojo.style(subnav_id, 'display', 'none');
							dojo.removeClass(nav_id, 'highlighted');
						}
					});
				}
			);

			dojo.query("#subNavigation .dropdown").forEach(
					function(dropdown, index, array){
						dojo.connect(dropdown, 'onmouseenter', function(item) {
							subnav_id = dropdown.id;
							nav_id = subnav_id.replace('subnav_', 'nav_');

							dojo.style(subnav_id, 'display', 'block');
							dojo.addClass(nav_id, 'highlighted');
						});

						dojo.connect(dropdown, 'onmouseleave', function(item) {
							subnav_id = dropdown.id;
							nav_id = nav_id.replace('subnav_', 'nav_');

							dojo.style(subnav_id, 'display', 'none');
							dojo.removeClass(nav_id, 'highlighted');
						});
					}
				);
		}
	);


function toggleGardenOptions() {
	if (dojo.byId('property-garden-1').checked) {
		dojo.style('property-largeGarden_row', 'display', 'block');
		dojo.style('property-communalGarden_row', 'display', 'none');
	} else if (dojo.byId('property-garden-0').checked) {
		dojo.style('property-largeGarden_row', 'display', 'none');
		dojo.style('property-communalGarden_row', 'display', 'block');
	} else {
		dojo.style('property-largeGarden_row', 'display', 'none');
		dojo.style('property-communalGarden_row', 'display', 'none');
	}
}

function toggleGarageOptions() {
	if (dojo.byId('property-garage-1').checked) {
		dojo.style('property-garageSize_row', 'display', 'block');
	} else if (dojo.byId('property-garage-0').checked) {
		dojo.style('property-garageSize_row', 'display', 'none');
	}
}

function toggleFeedbackExpected() {
	// which value is checked?
	var accuracy = '';

	dojo.query('#valuationFeedbackAccuracy_row input[type=radio]').forEach(
		function(item, index, array) {
			if (item.checked) {
				accuracy = item.value;
			}
		}
	);

	if (accuracy == 'high' || accuracy == 'low') {
		dojo.style('valuationFeedbackExpected_row', 'display', 'block');
	} else {
		dojo.style('valuationFeedbackExpected_row', 'display', 'none');
	}
}

function addressSearch() {
	dojo.style('address_search_spinner', 'display', 'inline');
	dojo.xhrGet({
	    url:"/valuation/postcode-lookup/?postcode=" + dojo.byId('address-postcode').value,
	    handleAs:"json",
	    timeout: 4000,
	    load: function(data){
			if (data[0]['Error'] && (data[0]['Error'] == '1002' || data[0]['Error'] == '1001')) {
				dojo.byId('postcodeLookupError').innerHTML = 'The postcode you entered does not appear to be valid. If you are sure you entered it correctly please enter the rest of your address in the fields above.';
				dojo.style('postcodeLookupError', 'display', 'inline-block');
				dojo.style('address_search_spinner', 'display', 'none');

				showAddressFields();
			} else if (data[0]['Error']) {
				addressSearchError();

			} else {
		        for(var i in data){
		        	dojo.create('option', {value: data[i]['Id'], innerHTML: data[i]['StreetAddress'] + ', ' + data[i]['Place']}, 'address_selector');
		        }
		        dojo.style('address_selector_row', 'display', 'block');
		        dojo.style('address_search_spinner', 'display', 'none');
			}
	    },
	    error: addressSearchError
	});
}

function addressSearchError() {
	dojo.byId('postcodeLookupError').innerHTML = 'Sorry, the postcode lookup feature is not currently available. Please enter your address details below.';
	dojo.style('postcodeLookupError', 'display', 'inline-block');
	dojo.style('address_search_spinner', 'display', 'none');

	showAddressFields();
}

function showAddressFields() {
	dojo.query('.addressEntry').style('display', 'block');
	dojo.style('address_manual_entry', 'display', 'none');
	dojo.style('address_lookup', 'display', 'none');
}

function showUnusualFeatures(type) {
	if (type == 'house') {
		unusualFeatures = ['conservatory', 'converted', 'additionalLand', 'barnsOutbuildings',
	                 'originalCharacterFeatures', 'grannyAnnexe', 'convertedLoft', 'electricGates', 'other',
	                 'riverSeaViews', 'paddock', 'stables', 'woodlandCountrysideViews', 'thatchedRoof',
	                 'cellarBasementRoom', 'gymnasium', 'utilityRoom', 'indoorPool', 'outdoorPool'];

	} else if (type == 'flat') {
		unusualFeatures = ['conciergePorterService', 'swimmingPool', 'riverSeaViews', 'duplexMultiLevels', 'originalCharacterFeatures',
	                'balcony', 'gymnasium', 'penthouse', 'woodlandCountrysideViews', 'conservatory',
	                'patioTerrace', 'other', 'utilityRoom'];
	}

	dojo.query('#property-unusualFeatures_row input[type=checkbox]').forEach(
		function(item, index, array){
			if (dojo.indexOf(unusualFeatures, item.value) != -1) {
				dojo.style(item.parentNode, 'display', 'block');
			} else {
				item.checked = false;
				dojo.style(item.parentNode, 'display', 'none');
			}
		}
	);
}

function hideUnusualFeatures() {
	dojo.style('property-unusualFeatures_row', 'display', 'none');

	dojo.query('#property-unusualFeatures_row input[type=checkbox]').forEach(
		function(item, index, array){
			item.checked = false;
		}
	);
}


function houseSalesLookup(postcode)
{
	console.log('running lookup');
	spinner = dojo.byId('houseSalesSpinner');
	if (spinner) {
		dojo.style(spinner, 'display', 'inline');
	}

    dojo.xhrGet({
        url: "/house-prices/sales.json?postcode=" + postcode,
        handleAs: "json",
        timeout: 8000,
        load: function(data){
            container = dojo.byId('recentSales');

            // remove existing table if there is one
            existingTable = dojo.query('#recentSales table');
            if (existingTable) {
            	dojo.destroy(existingTable[0]);
            }

            // remove error block if it exists
            if (dojo.byId('recentSalesLookupError')) {
            	dojo.destroy('recentSalesLookupError');
            }

            salesTable = dojo.create('table', {className: 'houseSales'});
            dojo.forEach(data, function(saleData, index){
            	addressString = saleData.address1;
            	if (saleData.address2 != '') {
            		addressString += ', ' + saleData.address2;
            	}
				if (saleData.address3 != '') {
            		addressString += ', ' + saleData.address3;
            	}
            	if (saleData.postcode != '') {
            		addressString += ', ' + saleData.postcode;
            	}
            	saleDate = saleData.saleDate.split('-').reverse().join('/');

                dojo.create('tr', {valign: 'top', innerHTML: '<td>' + saleDate + '</td><td>' + addressString + '</td><td>' + formatAmount(saleData.salePrice) + '</td>'}, salesTable);
            });

            //dojo.style(dojo.byId('mapValuationCta'), 'display', 'none');
            //dojo.style(dojo.byId('recentSales'), 'width', 'auto');
            //dojo.style(dojo.byId('recentSalesCancel'), 'display', 'inline');

            dojo.place(salesTable, 'recentSales');

        	spinner = dojo.byId('houseSalesSpinner');
            if (spinner) {
    			dojo.style(spinner, 'display', 'none');
    		}
        },
        error: function(error){
        	if (!dojo.byId('recentSalesLookupError')) {
        		dojo.create('div', {id: 'recentSalesLookupError', innerHTML: 'Sorry, no results were found for that postcode, please try another'}, 'recentSales');
        	}

        	spinner = dojo.byId('houseSalesSpinner');
            if (spinner) {
    			dojo.style(spinner, 'display', 'none');
    		}
        }
    });

    return true;
}


dojo.ready(function(){
	/*if (dojo.byId('recentSalesForm')) {
		recentSalesContainer = dojo.byId('recentSales');
		recentSalesSubmit = dojo.query('#recentSalesForm input[type=submit]')[0];
		recentSalesReset = dojo.query('#recentSalesForm input[type=reset]')[0];
		recentSalesPostcode = dojo.query('#recentSalesForm input[type=text]')[0];
		mapValuationCtaContainer = dojo.byId('mapValuationCta');

		// handle the form submit (perform lookup)
		dojo.connect(recentSalesSubmit, 'onclick', function(event){
			if (houseSalesLookup(recentSalesPostcode.value)) {
				dojo.style(recentSalesReset, 'display', 'inline');
				if (mapValuationCtaContainer) {
					dojo.style(recentSales, 'width', 'auto');
					dojo.style(mapValuationCtaContainer, 'display', 'none');
				}
			}

			dojo.stopEvent(event);
		});

		// handle enter in the postcode box (perform lookup)
		dojo.connect(recentSalesPostcode, 'onkeydown', function(event){
			if (event.keyCode == dojo.keys.ENTER) {
				if (houseSalesLookup(recentSalesPostcode.value)) {
					dojo.style(recentSalesReset, 'display', 'inline');
					if (mapValuationCtaContainer) {
						dojo.style(recentSales, 'width', 'auto');
						dojo.style(mapValuationCtaContainer, 'display', 'none');
					}
				}

				dojo.stopEvent(event);
			}
		});

		// handle cancel click (reset results)
		dojo.connect(recentSalesReset, 'onclick', function(event){
			salesTable = dojo.query("#recentSales table")[0];
			if (salesTable) {
				dojo.destroy(salesTable);
			}
			if (dojo.byId('recentSalesLookupError')) {
				dojo.destroy(dojo.byId('recentSalesLookupError'));
			}
			dojo.style(recentSalesReset, 'display', 'none');
			if (mapValuationCtaContainer) {
				dojo.style(recentSales, 'width', '50%');
				dojo.style(mapValuationCtaContainer, 'display', 'block');
			}
		});
	}*/
});


/* MWU */
dojo.ready(function () {
	if (dojo.byId('valuation_appraisal_enabled')) {
		if (!dojo.byId('valuation_appraisal_enabled').checked) {
			dojo.style('valuation_appraisalFields', 'display', 'none');
		}

		dojo.connect(dojo.byId('valuation_appraisal_enabled'), 'onclick', function() {
			if (dojo.byId('valuation_appraisal_enabled').checked) {
				dojo.style('valuation_appraisalFields', 'display', 'block');
			} else {
				dojo.style('valuation_appraisalFields', 'display', 'none');
			}
		});
	}
});

