jQuery.preloadImages = function()
{
  for(var i = 0; i<arguments.length; i++)
  {
    jQuery("<img>").attr("src", arguments[i]);
  }
}

$(document).ready(function() {
	initNav();
	initPayment();
	initEmailToFriend();
	
	initCarousel();
	initAgents();
	
	$('.jcarousel-next').hover(function() {
		$(this).addClass('jcarousel-next-hover');
	}, function() {
		$(this).removeClass('jcarousel-next-hover');
	});
	
	$('.jcarousel-prev').hover(function() {
		$(this).addClass('jcarousel-prev-hover');
	}, function() {
		$(this).removeClass('jcarousel-prev-hover');
	});
	
	$('.focus-clear').each(function(i, elem) {
		elem.original_value = elem.value;
	});
	$('.focus-clear').focus(function() {
		if(this.value == this.original_value) this.value = '';
	});
	$('.focus-clear').blur(function() {
		if(this.value == '') this.value = this.original_value;
	});
	
	$('#mls_number_submit').click(function() {
		location.href = Drupal.settings.mls.base_path + 'listings/view/' + $('#mls_number')[0].value;
	});
	
	$('#address_submit').click(function() {
		location.href = Drupal.settings.mls.base_path + 'listings/address-' + $('#address')[0].value.replace(/ /, '-');
	});
	
	$('#mls_form').bind('submit', function() {
		location.href = Drupal.settings.mls.base_path + 'listings/view/' + $('#mls_number')[0].value;
		return  false;
	});
	
	$('#address_form').bind('submit', function() {
		location.href = Drupal.settings.mls.base_path + 'listings/address-' + $('#address')[0].value.replace(/ /, '-');
		return  false;
	});
});

function initCarousel() {
	$('#listing_image_thumbnails ul').jcarousel({scroll:1});
	$('#listing_image_thumbnails img').each(function(i, elem) {
		$.preloadImages(elem.src.replace(/sub_property_detail_thumb_desat/, 'sub_property_detail_thumb'), elem.src.replace(/sub_property_detail_thumb_desat/, 'sub_property_mid'));
	});
	$('#listing_image_thumbnails img').hover(function() {
		this.src = this.src.replace(/sub_property_detail_thumb_desat/, 'sub_property_detail_thumb');
	}, function() {
		this.src = this.src.replace(/sub_property_detail_thumb/, 'sub_property_detail_thumb_desat');
	});
	$('#listing_image_thumbnails img').click(function() {
		$('#listing_large_image img')[0].src = this.src.replace(/sub_property_detail_thumb/, 'sub_property_mid');
		$('#listing_large_image a')[0].href = this.src.replace(/sub_property_detail_thumb/, 'sub_property_large');
	});
}

function initAgents() {
	$('.agent-teaser img').each(function(i, elem) {
		$.preloadImages(elem.src.replace(/agent_thumb/, 'agent_thumb_color'));
	});
	$('.agent-teaser img').hover(function() {
		this.src = this.src.replace(/agent_thumb/, 'agent_thumb_color');
	}, function() {
		this.src = this.src.replace(/agent_thumb_color/, 'agent_thumb');
	});
}

function initNav() {
	if($('#nav ul ul').length > 0) {
		$('#nav').addClass('active');
		var activeMenu = $('#nav ul>li.expanded');
		var parentIndex = activeMenu.siblings().andSelf().index(activeMenu);
		
		if(parentIndex > ($('#nav ul>li').length / 2)) {
			activeMenu.addClass('right');
		} else {
			activeMenu.addClass('left');
		}
	}
}

function initPayment() {
	if($('#mortgage_calculator').length > 0) {
		$('#mortgage_calculator').change(function() {
			paymentUpdate();
		});
		paymentUpdate();
	}
	if($('.mortgage_update').length > 0) {
			$('.mortgage_update').click(paymentUpdate);
	}
}

function paymentUpdate() {
	var amount = $('#mortgage_principal')[0].value.replace(/[\$,]+/g, "");
	var interest = Number($('#mortgage_interest')[0].value) / 100;
	var periods = $('#mortgage_periods')[0].value;
	var formatter = new NumberFormat(amount);
	
	formatter.setCurrency(true);
	formatter.setPlaces(0);
	$('#mortgage_principal')[0].value = formatter.toFormatted();
	
	var payment = mortgage_payment(amount, interest / 12, periods);
	var payment_formatter = new NumberFormat(payment);
	
	payment_formatter.setCurrency(true);
	payment_formatter.setPlaces(0); 

	$('#mortgage_payment').html(payment_formatter.toFormatted() + ' <span class="smaller">per month</span>');
}

function mortgage_payment(PR, IN, PE) {
	return (PR * IN) / (1 - Math.pow(1 + IN, -PE));
}

function initEmailToFriend() {
	$('#email_to_friend_form').validate();

	$('#email_to_friend_form').ajaxForm({beforeSubmit:function() {
		return $('#email_to_friend_form').valid();
	}, success:function() {
			$('.required_label').before('<span class="message">Successfully sent!</span>');
			$('.message').fadeOut('slow');
			setTimeout(tb_remove, 1000);
	}});
}

/* EmailLabs Validation Code */
function emailCheck (emailStr) {
var emailPat=/^(.+)@(.+)$/;
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
var validChars="\[^\\s" + specialChars + "\]";
var quotedUser="(\"[^\"]*\")";
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
var atom=validChars + '+';
var word="(" + atom + "|" + quotedUser + ")";
var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
var matchArray=emailStr.match(emailPat);
if (matchArray==null) {
	alert("Email address seems incorrect (check @ and .'s)");
	return false;
}
var user=matchArray[1];
var domain=matchArray[2];
if (user.match(userPat)==null) {
    alert("The username doesn't seem to be valid.");
    return false;
}
var IPArray=domain.match(ipDomainPat);
if (IPArray!=null) {
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
	        alert("Destination IP address is invalid!");
		return false;
	    }
    }
    return true;
}
var domainArray=domain.match(domainPat);
if (domainArray==null) {
	alert("The domain name doesn't seem to be valid.");
    return false;
}
var atomPat=new RegExp(atom,"g");
var domArr=domain.match(atomPat);
var len=domArr.length;
if ((domArr[domArr.length-1] != "info") &&
	(domArr[domArr.length-1] != "name") &&
	(domArr[domArr.length-1] != "arpa") &&
	(domArr[domArr.length-1] != "coop") &&
	(domArr[domArr.length-1] != "aero")) {
		if (domArr[domArr.length-1].length<2 || 
	    	domArr[domArr.length-1].length>3) {
		   		alert("The address must end in a three-letter domain, or two letter country.");
		   		return false;
		}
}
if (len<2) {
   var errStr="This address is missing a hostname!";
   alert(errStr);
   return false;
}
return true;
}

function UPTvalidateform(thisform)
{
	if (thisform.val_51913.value==""){	
alert("Please enter a value for Name");
return(true);}if (thisform.val_6.selectedIndex==0) { 
alert("Please select a value for State/Province");
 return(true);}
	if (emailCheck(thisform.email.value))
	{	
		alert('Thank you for signing up!');
		return false;
	}
	else
	{
		return true;
	}
}
/* End EmailLabs validation code */
