$(function() {
	//Get rid of dotted border on links and images when focused
	this.onfocusin = bluring;

	//Close Popups and Fade Layer
	$('a.close, #fade').live('click', function() { //When clicking on the close or fade layer...
		$('#fade , .popup_block').fadeOut(function() {
			$('#fade, a.close').remove();  //fade them both out
		});
		return false;
	});

	$.ajaxSetup({ cache: false });
});

function bluring() {
	if (event.srcElement.tagName == "A" || event.srcElement.tagName == "IMG")
		document.body.focus();
}

function imgError(source){
	source.src = "http://www.newstarrealty.com/img/noimage.gif";
	source.onerror = "";
	source.title = "";
	return true;
}

function showPopup(id, width, msg) {
	//Fade in the Popup and add close button
	$('#' + id).fadeIn().css({ 'width': Number( width ) }).prepend('<a href="#" class="close"><img src="/img/close_popup.gif" class="btn_close" title="Close Window" alt="Close" /></a>');

	//Define margin for center alignment (vertical   horizontal) - we add 80px to the height/width to accomodate for the padding  and border width defined in the css
	var popMargTop = ($('#' + id).height() + 80) / 2;
	var popMargLeft = ($('#' + id).width() + 80) / 2;

	//Apply Margin to Popup
	$('#' + id).css({
		'margin-top' : -popMargTop,
		'margin-left' : -popMargLeft
	});

	$('#msg').html(msg);

	//Fade in Background
	$('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
	$('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer - .css({'filter' : 'alpha(opacity=80)'}) is used to fix the IE Bug on fading transparencies 

	return false;
}

function submitForm(frm) {		
	var frmName = frm.name;
	
	var formName = "#" + frmName;
	var status_text = $(formName + "_status_text");
	var status = $(formName + "_status");
	status.css('background-color', 'black');
	status_text.html("<div style='padding-top:10px;'>Sending message<br>Please wait...</div>");
	status.fadeTo("fast", 0.8);	

	$.get(
		"/lib/form_" + frmName + ".asp", 
		$(formName).serialize(),
		function(data){				
			$(formName)[0].reset();				
			if (data == "success") {					
				status.fadeTo("fast", 0.3, function() {status_text.html("<br>Message Sent Successfully!");});
				status.fadeTo("fast", 0.8).delay(800).fadeOut(500);
			} else {				
				status.css('background-color', 'red');
				status.fadeTo("fast", 0.3, function() {status_text.html("Error Occured!<br>" + data);});
				status.fadeTo("fast", 0.8).delay(800).fadeOut(500);					
			}
		}
	);
}

function showForm(name) {
	var formName = "#" + name + "form";
	$(formName)[0].reset();
	$(formName + " span").each(function(){ $(this).html(""); });
	$(formName + "_status").css("opacity", "0");	
	$(formName + "_status").css("z-index", "-100");	
	showPopup(name + "popup", 500);
}

function checkForm(frm) {
	$("#" + frm.name + " span").each(function(){ $(this).html(""); });

	var regEmail = new RegExp(/^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z]{2,4}(.[a-zA-Z]{2})?$/);	
	var	errorCount = 0;

	if (!(regEmail.test(frm.email.value))) {
		$("#email_error").html("<span class='popup_error_text'>Please enter a vaild email.</span>");
		errorCount++;
	}

	if (frm.phone.value != "") {
		if (frm.phone.value.search(/\d{3}\-\d{3}\-\d{4}/) == -1) {
			$("#phone_error").html("<span class='popup_error_text'>Please enter a vaild phone number.</span>");
			errorCount++;
		}
	}
	
	if (frm.message.value.length < 5) {
		$("#message_error").html("<span class='popup_error_text'>Please enter more words.</span>");
		errorCount++;
	}

	if (errorCount == 0)
		submitFormAlt(frm.name);
}

function submitFormAlt(name){
	var formName = "#" + name;
	var status_text = $(formName + "_status_text");
	var status = $(formName + "_status");
	status.css('z-index', '100');	
	status.css('background-color', 'black');
	status_text.html("<div style='padding-top:40%;color:#dedede;'>Sending message<br>Please wait...</div>");
	status.fadeTo("fast", 0.9);

	$.ajax({ 
		url: "/lib/form_" + name.replace("form", "") + ".asp", 
		type: "POST", 
		data: $(formName).serialize(), 
		contentType: "application/x-www-form-urlencoded; charset=utf-8", 
		dataType: "text", 
		success: function(data){
			$(formName)[0].reset();				
			if (data == "success") {					
				status.fadeTo("fast", 0.3, function() {status_text.html("<div style='padding-top:40%;color:#dedede;'>Message Sent Successfully!</div>");});
				status.fadeTo("fast", 0.8).delay(800).fadeOut(500);
			} else {				
				status.css('background-color', 'red');
				status.fadeTo("fast", 0.3, function() {status_text.html("<div style='padding-top:40%;color:#dedede;'>Error Occured!<br>" + data + "</div>");});
				status.fadeTo("fast", 0.8).delay(800).fadeOut(500);					
			}
		}
	});
}

// Bing Map Related Functions

function GetDistance(lat1, lon1, lat2, lon2, unit) {
	var radlat1 = Math.PI * lat1/180;
	var radlat2 = Math.PI * lat2/180;
	var radlon1 = Math.PI * lon1/180;
	var radlon2 = Math.PI * lon2/180;
	var theta = lon1-lon2;
	var radtheta = Math.PI * theta/180;
	var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
	dist = Math.acos(dist);
	dist = dist * 180/Math.PI;
	dist = dist * 60 * 1.1515;
	if (unit=="K") { dist = dist * 1.609344 };
	if (unit=="N") { dist = dist * 0.8684 };
	return dist;
} 

function CallRestService(request) 
{
	var script = document.createElement("script");
	script.setAttribute("type", "text/javascript");
	script.setAttribute("src", request);
	document.body.appendChild(script);
}
