
/********************************************************************************
*
* DROdio site-wide common functions
*
*
********************************************************************************/
var drodio_main = {
	
	path: '',
	
	// -----------------------------------------------------------------------
	
	//main initialize function
	init: function(url_path) {
		
		this.path = url_path;
		
		$('button.theme-button').button();
		
		// enable fancybox
		if($.fn.fancybox) {
			$('.img-fancybox').fancybox({
				type: 'image'
			});
		}
			
		//display feedback dialog
		$('#feedback-dialog-link').click(function() {
			$('#feedback-dialog').dialog({
				title: "Submit Website Feedback",
				width: 600,
				modal: true
			});	
			return false;
		});
		$('#feedback-dialog-form').submit(function () {return drodio_main.submitFeedback();});
		
		$('#property-search form').submit(function() {
			if($('#property-search-input-q').val() == $('#property-search-input-q').attr('placeholder')) {
				$('#property-search-input-q').val('');
			}
		});	
				
		$('#schedule-coffee-form').submit(function() {return drodio_main.scheduleCoffee();});

		$('#agent-referral-dialog-form').submit(function() {return drodio_main.submitReferral();});
		
		if (!Modernizr.input.placeholder) {
			$('input').each(function() {
				if ($(this).val() == '' && $(this).attr('placeholder') != '') {
					$(this).val($(this).attr('placeholder'));
					$(this).focus(function() {
						if ($(this).val() == $(this).attr('placeholder')) {
							$(this).val('');
						}
					});
					$(this).blur(function() {
						if ($(this).val() == '') {
							$(this).val($(this).attr('placeholder'));
						}
					});
				}
			});
		}
		
		drodio_properties.init();
		drodio_expertadvice.init();
		
		//this.addSiteNotice();
		
		this.visitorTracker.init();
	},
	
	// -----------------------------------------------------------------------
	
	submitFeedback: function() {

		if ($('#InquiryFirstName').val() == '' || $('#InquiryLastName').val() == '') {
			alert('Please fill out first name and last name field');
			return false;
		}
		
		if ($('#InquiryEmail').val() == '' && $('#InquiryPhone').val() == '') {
			alert('You need to provide an email or phone');
			return false;
		}

		$('#feedback-dialog-form button').button({disabled:true});

		url = drodio_main.path + 'ajax/inquiries/feedback';		
		$.ajax({
			type: 'POST',
			url: url,
			data: $('#feedback-dialog-form').serialize(),
			success: function(data) {
				$('#feedback-dialog-form-message').html(data).show();
				$('#feedback-dialog-form button').button({disabled:false});
			}
		});
		
		return false;
	},

	// -----------------------------------------------------------------------

	submitReferral: function() {
		$('#agent-referral-dialog-form button').button({disabled: true});
		url = drodio_main.path + 'ajax/inquiries/referrals';
		$.ajax({
			type: 'POST',
			url: url,
			data: $('#agent-referral-dialog-form').serialize(),
			success: function(data) {
				$('#agent-referral-dialog-form-message').html(data).show();
				$('#agent-referral-dialog-form button').button({disabled:false});
			}
		});

		return false;
	},
	
	// -----------------------------------------------------------------------
	
	scheduleCoffee: function() {
		$('#schedule-coffee-form button').button({disabled:true});
		url = drodio_main.path + 'ajax/inquiries/feedback';		
		$.ajax({
			type: 'POST',
			url: url,
			data: $('#schedule-coffee-form').serialize(),
			success: function(data) {
				$('#schedule-coffee-form-message').html(data).show();
				$('#schedule-coffee-form button').button({disabled:false});
			}
		});
		
		return false;
	},
	
	// -----------------------------------------------------------------------
	
	recordOutboundLink: function() {
		//get all outboundlink. those links using rel=external
		
	},
	
	// -----------------------------------------------------------------------
	
	registerPageView: function(page_url) {
		if (typeof _gaq != 'undefined') {
			// google analytics goal => /property/inquiry/showform
			//_gaq.push(['_trackEvent','Property Inquiry','Button Clicked','Property Inquiry Step 1']);
		
			//var pageTracker = _gat._getTracker("UA-15412310-1");
			//pageTracker._trackPageview("/property/inquiry/showform");
			
			_gaq.push(['_trackPageview', page_url]);
		}
	},
	
	// -----------------------------------------------------------------------
	
	addSiteNotice: function() {
		$('<div></div>').attr('id', 'attention').attr('style', 'display:none').append('<strong>New DROdio website launched.</strong> You can still access the old website at <a href="http://old.drodio.com/" target="_new" rel="nofollow">old.drodio.com</a>').prependTo('body');
		$('#attention').slideDown();
	},
	
	// -----------------------------------------------------------------------
	
	visitorTracker: {
		
		//tracking variables
		landing: '',
		steps: '',
		path: '',
		referrer: '',
		
		createCookie: function(name, value, days) {
			if (days) {
				var date = new Date();
				date.setTime(date.getTime()+(days*24*60*60*1000));
				var expires = "; expires="+date.toGMTString();
			} else {
				var expires = "";
			}
			document.cookie = name+"="+value+expires+"; path=/";
		},
		
		readCookie: function(name) {
			var nameEQ = name + "=";
			var ca = document.cookie.split(';');
			for (var i=0; i<ca.length; i++) {
				var c = ca[i];
				while (c.charAt(0) == ' ') {
					c = c.substring(1, c.length);
				}
				if (c.indexOf(nameEQ) == 0) {
					return c.substring(nameEQ.length, c.length);
				}
			}
			return null;
		},
		
		eraseCookie: function(name) {
			this.createCookie(name, "", -1);
		},
		
		initCookies: function(delCookie) {
			if (delCookie == 1) {
				this.eraseCookie('external_referrer');
				this.eraseCookie('landing_page');
				this.eraseCookie('path');
				this.eraseCookie('total_steps');
			}
			
			this.referrer = document.referrer;
			this.landing = window.location.href;
			this.steps = 1;
			
			if (this.referrer.length > 0) {
				this.path = this.referrer + ' -> ' + this.landing;
			} else {
				this.path = 'Direct Address Input' + ' -> ' + this.landing;
			}
			
			this.createCookie('external_referrer', this.referrer, 1);
			this.createCookie('landing_page', this.landing, 1);
			this.createCookie('total_steps', this.steps, 1);
			this.createCookie('path', this.path);
		},
		
		addToForm: function(form_id) {
			$('<input type="hidden" name="tracking_referrer" value="'+this.referrer+'" /><input type="hidden" name="tracking_landing" value="'+this.landing+'" /><input type="hidden" name="tracking_steps" value="'+this.steps+'" /><input type="hidden" name="tracking_path" value="'+this.path+'" />').appendTo('#'+form_id);
		},
		
		init: function() {
			var url_referral = this.readCookie('external_referrer');
			
			if (url_referral == null) {
				this.initCookies(0);
			} else {
				var ref_url = document.referrer;
				var curr_url = document.domain;
				if (1 < ref_url.indexOf(curr_url)) {
					this.steps = this.readCookie('total_steps');
					this.steps++;
					this.createCookie('total_steps', this.steps, 1);
					
					this.path = this.readCookie('path');
					this.path = this.path + ' -> ' + window.location.href;
					this.createCookie('path', this.path);
					
					this.referrer = this.readCookie('external_referrer');
					this.landing = this.readCookie('landing_page');
				} else {
					this.initCookies(1);
				}
			}
		}
	
	}
	
}; /* END OF DRODIO MAIN */


/********************************************************************************
*
* DROdio Expert Advice specific functions
*
*
********************************************************************************/
var drodio_expertadvice = {

	init: function() {
		$('#share-email-dialog-link').click(function() {
			$('#share-email-dialog').dialog({
				title: "Share with friends",
				width: 600,
				resizable: false,
				modal: true
			});
			return false;
		});
		
		$('#share-email-dialog-form').submit(function() {return drodio_expertadvice.shareEmail();});
	},
	
	// -----------------------------------------------------------------------
	
	shareEmail: function() {
		var url = drodio_main.path + 'ajax/inquiries/share_via_email';
	
		$('#share-email-dialog-form button').button({disabled:true});
		
		$.ajax({
			type: 'POST',
			url: url,
			data: $('#share-email-dialog-form').serialize(),
			success: function(data) {
				$('#share-email-dialog fieldset').html(data);
				$('#share-email-dialog-form button').button({disabled:false});
			}
		});
			
		return false;
	}
	

}; /* END OF DRODIO EXPERT ADVICE */


/********************************************************************************
*
* DROdio Property specific functions
*
*
********************************************************************************/
var drodio_properties = {

	init: function() {
		
		$('#property-search .advanced-link').click(function() { 
			$('#property-search-advanced').toggle(function() {
				if($('#property-search-advanced').is(':visible')) {
					$('#property-search .advanced-link').html('Hide Advanced Search Option');
					$('#property-search-advanced .input').removeAttr('disabled');
				} else {
					$('#property-search .advanced-link').html('Advanced Search Options');
					$('#property-search-advanced .input').attr('disabled', 'disabled');
				}
			}); 
			return false;
		});
		
		$('#property-page-details').tabs();
		
		$('#property-image-holder a.more-photos').click(function() {
			$.scrollTo('#property-page-action', 800);
			$('#property-page-details').tabs('select', 'property-photos');
			return false;
		});
		
		if (!$.browser.msie) {
			if ($.fn.corner) {
				$('#property-page-action').corner('5px');
				$('#property-page-type div').corner('tl 3px');
				$('#property-page-request-info-form').corner('5px');
				$('.rounded').corner('5px');
			}
		}
		
		$('table.alternate tr:even').addClass('alt');
		
		$('#property-page-action-button').click(function() {
			drodio_main.registerPageView('/property/inquiry/showform');
			$.scrollTo('#property-page-request-info-form', 800);
			return false;
		});
		
		$('#property-inquiry-form').submit(function() { 
			$('#property-inquiry-form .loading-indicator').show();
			drodio_main.registerPageView('/property/inquiry/thankyou');
			drodio_properties.submitInquiry('property-inquiry-form');
			$('#property-inquiry-form .loading-indicator').hide();
			return false;
		});
		
		// inquiry comments toggle link
		$('#property-inquiry-comments-switch').click(function() {
			$('#property-inquiry-comments-input').show();
			$('#property-inquiry-comments-switch').hide();
			return false;
		});	
		
		$('#property-watch-dialog-link').click(function() {
			drodio_main.registerPageView('/property/inquiry/show/addwatch');
			$('#property-watch-dialog').dialog({
				title: 'Watch this Property',
				draggable: false,
				modal: true,
				resizable: false,
				width: 400
			});
			return false;
		});
				
		$('#property-watch-dialog-form').submit( function() {
			drodio_main.registerPageView('/property/inquiry/addwatch');
			drodio_properties.submitInquiry('property-watch-dialog-form');
			return false;
		});
		
		$('#property-ask-dialog-link').click(function() {
			drodio_main.registerPageView('/property/inquiry/show/ask');
			$('#property-ask-dialog').dialog({
				title: 'Ask a Question on this Property',
				draggable: false,
				modal: true,
				resizable: false,
				width: 400
			});
			return false;
		});
		
		$('#property-ask-dialog-form').submit( function() {
			drodio_main.registerPageView('/property/inquiry/ask');
			drodio_properties.submitInquiry('property-ask-dialog-form');
			return false;
		});
		
		$('#property-neighborhood-dialog-link').click(function() {
			drodio_main.registerPageView('/property/inquiry/show/neighborhoodreport');
			$('#property-neighborhood-dialog').dialog({
				title: 'Get a Neighborhood Report',
				draggable: false,
				modal: true,
				resizable: false,
				width: 400
			});
			return false;
		});
		
		$('#property-neighborhood-dialog-form').submit( function() {
			drodio_main.registerPageView('/property/inquiry/neighborhoodreport');
			drodio_properties.submitInquiry('property-neighborhood-dialog-form');
			return false;
		});
		
		$('#property-morephoto-dialog-link').click(function() {
			drodio_main.registerPageView('/property/inquiry/show/morephoto');
			$('#property-morephoto-dialog').dialog({
				title: 'Request More Photos',
				draggable: false,
				modal: true,
				resizable: false,
				width:400
			});
			return false;
		});
		
		$('#property-morephoto-dialog-form').submit( function() {
			drodio_main.registerPageView('/property/inquiry/morephoto');
			drodio_properties.submitInquiry('property-morephoto-dialog-form');
			return false;
		});
		
		//toggle link on browse by area breadcrumb
		$('#property-browsebyarea .toggle').click(function() {
			if ($('#property-browsebyarea .browse').is(':hidden')) {
				$('#property-browsebyarea .browse').slideDown();
				$('#property-browsebyarea .toggle').text('Hide Panel');
			} else {
				$('#property-browsebyarea .browse').slideUp();
				$('#property-browsebyarea .toggle').text('Show other areas');
			}
			return false;
		});
	},
	
	// -----------------------------------------------------------------------
	
	//initialize google map on property page
	initGoogleMap: function(latitude,longitude) {
	
		var latlng = new google.maps.LatLng(latitude, longitude);

		var map_options = {
			zoom: 19,
			center: latlng,
			mapTypeId: google.maps.MapTypeId.HYBRID
		};
	
		var map = new google.maps.Map(document.getElementById('gmap_canvas'), map_options);
		
		var marker = new google.maps.Marker({
			position: latlng,
			map: map,
			title: "Property"
		});
	},
	
	// -----------------------------------------------------------------------
	
	//initialize google map on city listing page
	initGoogleMapCity: function(city_name, state) {
		
		var url = drodio_main.path + 'ajax/properties/getbycity/' + city_name + '/' + state + '/drodio/' + 100;
		var property_array = new Array();
		var property_data = new Array();
		
		var geocoder = new google.maps.Geocoder();
		var map_center = new google.maps.LatLng(0,0);
		
		geocoder.geocode({'address': city_name + ", " + state}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				map_center = results[0].geometry.location;
				map.setCenter(results[0].geometry.location);
			}
		});
		
		var map_options = {
			zoom: 12,
			center: map_center,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
	
		var map = new google.maps.Map(document.getElementById('gmap_canvas'), map_options);
		var latLngBounds = new google.maps.LatLngBounds();
		var infoWindow = new google.maps.InfoWindow({});
		
		$.ajax({url:url, dataType: 'json', async: false, success: function(data) {
			$.each(data, function(i, item) {
				
				if ((item.Property.Latitude != 0 && item.Property.Latitude != '') && (item.Property.Longitude != 0 && item.Property.Longitude != '')) {
					
					var latlng = new google.maps.LatLng(item.Property.Latitude, item.Property.Longitude);
					latLngBounds.extend(latlng);
					
					var icon = '';
					if (item.Property.ForSale == 'Y') {
						icon = drodio_main.path + 'img/map-icons/home-sale.png';
					} else {
						icon = drodio_main.path + 'img/map-icons/home-rent.png';
					}
					
					var marker = new google.maps.Marker({position: latlng, map: map, title: item.Property.FullStreetAddress, icon: icon});
					
					marker.infoWindowHtml = '<div>' + '<img src="' + item.Property.ListPictureURL + '" alt="" width="100" height="80" style="float:left; border:1px solid #ccc; margin-right:8px;" />' + '<h3 style="margin-bottom:5px;">' + item.Property.FullStreetAddress + '</h3>' + '<p style="margin:0;">List Price:<strong>$' + item.Property.ListPrice + '</strong>, Beds:<strong>' + item.Property.Beds + '</strong>, Baths:<strong>' + item.Property.Baths + '</strong>, MLS:<strong>' + item.Property.ListingID + '</strong>. <br /><a href="' + item.Property.URL + '" style="color:#00c; font-weight:bold;">View Property Details</a></p>' + '</div>';
					google.maps.event.addListener(marker, 'click', function() {infoWindow.setContent(marker.infoWindowHtml);infoWindow.open(map, marker);});
				}
				
			});
		}});
		
		map.fitBounds(latLngBounds);
	},
	
	// -----------------------------------------------------------------------
	
	//initialize google map on property search results page
	initGoogleMapSearch: function(search_results) {
		
		var map_center = new google.maps.LatLng(0,0);
		
		var map_options = {
			zoom: 16,
			center: map_center,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
	
		var map = new google.maps.Map(document.getElementById('gmap_canvas'), map_options);
		var latLngBounds = new google.maps.LatLngBounds();
		var infoWindow = new google.maps.InfoWindow({});
		var lastLatLng;
		
		$.each(search_results, function(i, item) {
			
			if ((item.Property.Latitude != 0 && item.Property.Latitude != '') && (item.Property.Longitude != 0 && item.Property.Longitude != '')) {
				
				var forSale = 'SALE';
				var icon = '';
				if (item.Property.ForSale == 'Y') {
					icon = drodio_main.path + 'img/map-icons/home-sale.png';
				} else {
					forSale = 'RENT';
					icon = drodio_main.path + 'img/map-icons/home-rent.png';
				}
				
				var latlng = new google.maps.LatLng(item.Property.Latitude, item.Property.Longitude);
				var marker = new google.maps.Marker({position: latlng, map: map, title: '', icon: icon});
				
				marker.infoWindowHtml = '<div>' + '<img src="' + item.Property.ListPictureURL + '" alt="" width="100" height="80" style="float:left; border:1px solid #ccc; margin-right:8px;" />' + '<h3 style="margin-bottom:5px;">' + item.Property.FullStreetAddress + '</h3>' + '<p style="margin:0;">List Price:<strong>$' + item.Property.ListPrice + '</strong>, Beds:<strong>' + item.Property.Beds + '</strong>, Baths:<strong>' + item.Property.Baths + '</strong>, MLS:<strong>' + item.Property.ListingID + '</strong>. <br /><a href="' + drodio_properties.buildPropertyUrl(item.Property.FullStreetAddress, item.Property.CityName, item.Property.State, item.Property.ListingID) + '" style="color:#00c; font-weight:bold;">View Property Details</a></p>' + '</div>';
				
				google.maps.event.addListener(marker, 'click', function() {infoWindow.setContent(marker.infoWindowHtml);infoWindow.open(map, marker);});
				
				google.maps.event.addListener(marker, 'mouseover', function() {$('#gmap_overlay .wrap').html('<div>' + '<img src="' + item.Property.ListPictureURL + '" alt="" width="240" height="120" style="border:1px solid #ccc; background:#999;" /><br />' + '<h3 style="margin:5px 0 3px;">' + item.Property.FullStreetAddress + '</h3>' + '<p style="margin:0 0 3px; padding:0; line-height:15px;">Property for <strong>'+ forSale + '</strong>. List Price:<strong>$' + item.Property.ListPrice + '</strong>, Beds:<strong>' + item.Property.Beds + '</strong>, Baths:<strong>' + item.Property.Baths + '</strong>, MLS:<strong>' + item.Property.ListingID + '</strong>. <br /><a href="' + drodio_properties.buildPropertyUrl(item.Property.FullStreetAddress, item.Property.CityName, item.Property.State, item.Property.ListingID) + '" style="display:block; width:80%; height:30px; line-height:30px; margin:0 auto; color:#fff; text-align:center; background:#06C; border:2px solid #fff; margin-top:6px; font-weight:bold;">View Property Details</a></p>' + '</div>');});
				
				latLngBounds.extend(latlng);
				lastLatLng = latlng;
			}
		
		});
		
		map.fitBounds(latLngBounds);
		map.setCenter(lastLatLng);
		map.setZoom(12);
	},
	
	// -----------------------------------------------------------------------
	
	initBingMap: function(latitude,longitude) {
		
		var bingApiKey = 'AkhTRbekdl02yKlT9ASvhB6wX1o8AznH-yZtf_yIv2yv_kddX7iNYMhbmVGPcUS8';
		var map = new VEMap('bmap_canvas');
		map.SetCredentials(bingApiKey);
		
		var location = new VELatLong(latitude, longitude, 604, VEAltitudeMode.RelativeToGround);
		
		map.LoadMap(location, 19, VEMapStyle.Oblique, false);
		
		var pushpin = new VEShape(VEShapeType.Pushpin, location);
		map.AddShape(pushpin);
	},
	
	// -----------------------------------------------------------------------
	
	submitInquiry: function(form_id) {
		
		var url = drodio_main.path + 'ajax/inquiries/submit';
		
		var form_status = false;
		
		//validate form
		//require first and last name
		if ($('#'+form_id + ' .input_first_name').val() == '' || $('#'+form_id + ' .input_last_name').val() == '') {
			alert('Please fill out first name and last name field');
			return false;
		}
		//check if there's email or phone
		if ($('#'+form_id + ' .input_email').val() == '' && $('#'+form_id + ' .input_phone').val() == '') {
			alert('You need to provide an email or phone');
			return false;
		}
		
		drodio_main.visitorTracker.addToForm(form_id);
		
		$.ajax({
			type: 'POST',
			url: url,
			data: $('#'+form_id).serialize(),
			success: function(data) {
				//$('#'+form_id).unblock();
				
				$('#' + form_id + ' .form-message').html(data).show();
				form_status = true;
			}
		});
		
		return form_status;
	},
	
	// -----------------------------------------------------------------------
	
	loadPropertyListAside: function(city_name, state, mls) {
		
		var url = drodio_main.path + 'ajax/properties/getbycity/' + city_name + '/' + state + '/' + mls;
		
		$.getJSON(url, function(data) {
			$.each(data, function(i, item) {
				$('<li><img src="' + item.Property.ListPictureURL + '" alt="" width="183" height="100" /><a href="' + item.Property.URL + '">' + item.Property.FullStreetAddress + ', ' + city_name + '</a></li>').appendTo('#property-aside-bycity ul');
			});
		});

	},
	
	// -----------------------------------------------------------------------
	
	buildPropertyUrl: function(street_address, city, state, mls) {
	
		var url = drodio_main.path;
		
		if (state == 'VA') {
			url = url + 'virginia-real-estate/';
		} else if (state == 'MD') {
			url = url + 'maryland-real-estate/';
		} else if (state == 'DC') {
			url = url + 'washington-dc-real-estate/';
		} else if (state == 'DE') {
			url = url + 'delaware-real-estate/';
		} else if (state == 'PA') {
			url = url + 'pennsylvania-real-estate/';
		} else if (state == 'WV') {
			url = url + 'west-virginia-real-estate/';
		} else {
			
		}
		
		url = url + city.toLowerCase().replace(/[^\w ]+/g, '').replace(/ +/g, '-') + '/';
		url = url + street_address.toLowerCase().replace(/[^\w ]+/g, '').replace(/ +/g, '-') + '-' + city.toLowerCase().replace(/[^\w ]+/g, '').replace(/ +/g, '-') + '-' + state.toLowerCase() + '-' + mls.toLowerCase() + '.php';
		
		return url;
	},
	
	// -----------------------------------------------------------------------
	
	mortgageCalculator: {
		
		init: function() {
			
			var interest_rate_slider = $('<div id="interest-rate-slider" style="margin-top:5px;"></div>').insertAfter($('#interest-rate-input')).slider({
				value: $('#interest-rate-input').val().replace(/ %/, ''),
				min: 0,
				max: 10,
				step: 0.1,
				slide: function(event, ui) {
					$('#interest-rate-input').val(ui.value + ' %');
				},
				stop: function() {
					drodio_properties.mortgageCalculator.calculate();
				}
			});
			$('#interest-rate-input').change(function() {
				
				if ($('#interest-rate-input').val().replace(/ %/, '') > 0 && $('#interest-rate-input').val().replace(/ %/, '') < 10) {
					interest_rate_slider.slider('value', $('#interest-rate-input').val().replace(/ %/, ''));
					$('#interest-rate-input').val($('#interest-rate-input').val().replace(/ %/, '') + ' %');
					drodio_properties.mortgageCalculator.calculate();
				} else {
					alert('Valid interest rate range is 1-10. Use the slider to choose interest rate.');
					$('#interest-rate-input').val(interest_rate_slider.slider('value') + ' %');
				}
			});
			
			var downpayment_slider = $('<div id="downpayment-slider" style="margin-top:5px;"></div>').insertAfter($('#downpayment-input')).slider({
				value: 20,
				min: 0,
				max: 100,
				step: 1,
				slide: function(event, ui) {
					$('#downpayment-input').val((ui.value / 100) * $('#house-price-input').val());
					$('#downpayment-percent').text(ui.value);
				},
				stop: function() {
					drodio_properties.mortgageCalculator.calculate();
				}
			});
			$('#downpayment-input').change(function() {
				if ($('#downpayment-input').val() >= 0 && $('#downpayment-input').val() < $('#house-price-input').val()) {
					percentage = ($('#downpayment-input').val() / $('#house-price-input').val()) * 100;
					downpayment_slider.slider('value', percentage);
					$('#downpayment-percent').text(percentage);
					drodio_properties.mortgageCalculator.calculate();
				} else {
					alert('Maximum downpayment is equal to house price');
					$('#downpayment-percent').text(20);
					downpayment_slider.slider('value', 20);
					$('#downpayment-input').val((20 / 100) * $('#house-price-input').val());
					
					drodio_properties.mortgageCalculator.calculate();
				}
			});
			
			$('#term-input').change(function() { drodio_properties.mortgageCalculator.calculate(); });
			
			drodio_properties.mortgageCalculator.calculate();
		},
		
		calculate: function() {
			
			house_price = $('#house-price-input').val();
			downpayment = $('#downpayment-input').val();
			term = $('#term-input').val();
			
			principal = house_price - downpayment;
			total_months = term * 12;
			monthly_payment = 0;
			
			if ($('#interest-rate-input').val().replace(/ %/, '') != 0) {
				interest_rate = ($('#interest-rate-input').val().replace(/ %/, '') / 100) / 12;
				monthly_payment = Math.floor((principal * interest_rate) / (1 - Math.pow(1 + interest_rate, (-1 * total_months))) * 100) / 100;
			} else {
				monthly_payment = principal / total_months;
			}
			
			$('#monthly-payment-label span').text(Math.round(monthly_payment)).parent().effect('highlight');
		}
	}
	
}; /* END OF DRODIO_PROPERTY */

