/* Listing page common   */
function Page_OnLoad()
{
   document.getElementById('aspnetForm').action = document.getElementById('aspnetForm').action+'#inquireForm';
}

function topWindow(){
	popup = window.open("popupcalendar.htm","","height=220,width=250,scrollbars=no");
}

function winopen(url,a,b){
    newwin=window.open(url,a,b)
}

function ClearCookies() {
	deleteCookie("Visitor", "/global", document.domain);
	deleteCookie("Trip", "/global", document.domain);
	document.forms[0].fullName.value = "";
	document.forms[0].emailAddress.value = "";
	document.forms[0].reEnterEmailAddress.value = "";
	document.forms[0].homePhone.value = "";
	document.forms[0].desiredArrivalDate.value = "";
	document.forms[0].lengthOfStay.value = "";
	document.forms[0].numberInParty.value = "";
	document.forms[0].Comments.value = "";
}

function setCookie(name, value, expires, path, domain, secure) {
	document.cookie = curCookie = name + "=" + escape(value) + ((expires) ? "; expires=" + expires.toGMTString() : "") + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : "");
}

function getCookie(name) {
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	} else begin += 2;
	var end = document.cookie.indexOf(";", begin);
	if (end == -1) end = dc.length;
	return unescape(dc.substring(begin + prefix.length, end));
}

function deleteCookie(name, path, domain) {
	if (getCookie(name)) document.cookie = name + "=" + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
}

function fixDate(date) {
	var base = new Date(0);
	var skew = base.getTime();
	if (skew > 0) date.setTime(date.getTime() - skew);
}


/*
Form field Limiter script- By Dynamic Drive
For full source code and more DHTML scripts, visit http://www.dynamicdrive.com
This credit MUST stay intact for use
*/
//jrs - note that I have modified this heavily
function restrictchar(event,spanid,theFormField,maxlength)
{
    if(event.target.value != 'undefined' && event.target.value.length>=maxlength) {
        var pressedkey=/[a-zA-Z0-9\.\,\/]/ //detect alphanumeric keys
        if (pressedkey.test(String.fromCharCode(event.which))) {
            event.stopPropagation()
        }
    }
    else {
        return false;
    }
    return true;
}

function restrictcharIE(maxlength)
{
    if (window.event && (event.srcElement.value.length>=maxlength)) {
        var pressedkey=/[a-zA-Z0-9\.\,\/]/ //detect alphanumeric keys
        if (pressedkey.test(String.fromCharCode(event.which))) {
            event.stopPropagation()
        }
    }
}

function limitcountcharsIE(commentelement,maxlength,spanelement)
{
    lengthleft=maxlength-commentelement.value.length;
    if (lengthleft < 0) {
        commentelement.value=commentelement.value.substring(0,maxlength);
        lengthleft = 0;
    }
    spanelement.innerHTML= "(" + lengthleft + " Characters)";
    
}

function limitcountchars(event,spanid,theFormField,maxlength)
{
    spanelement = document.getElementById(spanid);
    lengthleft=maxlength-theFormField.value.length;
    if (lengthleft<0) {
        theFormField.value=theFormField.value.substring(0,maxlength);
        spanelement.innerHTML= "(0 Characters)";
    }
    else {
        spanelement.innerHTML= "(" + lengthleft + " Characters)";
    }
    
}

function limitcharsinfield(theFormField, thelimit, spanid, fieldname) {
    if (theFormField != null) {
        //the form field may not exist - that is valid for listing page in review mode
        lengthleft = thelimit;
    	lengthleft -= theFormField.value.length;
    	spanelement = document.getElementById(spanid);
    	spanelement.innerHTML= "(" + lengthleft + " Characters)";
    
    	if (typeof document.all == 'undefined') {
        	document.body.addEventListener('keypress', function(event) { restrictchar(event,spanid,theFormField,thelimit) }, true); 
        	document.body.addEventListener('keyup', function(event) { limitcountchars(event,spanid,theFormField,thelimit) }, true); 
    	}
    	else {
        	//IE does it differently
	        commentelement = document.all[fieldname];
    	    commentelement.onkeypress=function(){ restrictcharIE(thelimit) }
        	commentelement.onkeyup=function(){ limitcountcharsIE(commentelement,thelimit,spanelement) }
    	}
    }

}

/* Listing page common */
$('.readmore').click(function(){
    if($(this).text() == "Read more")
    {
       $(this).text("Collapse");
    }
    else
    {
      $(this).text("Read more");
    }
    $(this).parent().next().toggle();
    return false;
});


/* Google Maps stuff */
var OwnerMaps_MapList = new Array();
var OwnerMaps_HomeMarker = null;
function GetMarker(letter)
{
	for (var i = 0; i < OwnerMaps_MapList.length; i++)
	{
		if (OwnerMaps_MapList[i].Letter == letter)
		{
			return OwnerMaps_MapList[i];
		}
	}
	return null;
}

function ShowInfoBubble(forWhat)
{
	if (forWhat == "HomeMarker")
	{
		if (OwnerMaps_HomeMarker != null)
		{
			OwnerMaps_HomeMarker.openInfoWindow('<p class="MapPrpDesc">' + FixCommas(unescape(ownerMap.desc)) + "</p>");
		}
	}
	else
	{
		var idx = parseInt(forWhat);
		var geoMarker = OwnerMaps_MapList[idx];
		if (geoMarker != null)
		{
			geoMarker.openInfoWindowHtml(GetBubbleHtml(geoMarker));
		}
	}
}

var map;

// Call this function when the page has been loaded
function mapsLoaded()
{
	map = new GMap2(document.getElementById("BtmMap"));
	map.setCenter(new google.maps.LatLng(ownerMap.lat, ownerMap.lng), ownerMap.zoom);
	map.addControl(new GMapTypeControl());
	map.addControl(new GSmallMapControl());

	SetMapType();

	if (ownerMap.fixZoom)
	{
	   //don't allow user to zoom in more than the owner wants
	   G_PHYSICAL_MAP.getMaximumResolution = function() { return ownerMap.zoom };
	   G_NORMAL_MAP.getMaximumResolution = function() { return ownerMap.zoom };
	   G_SATELLITE_MAP.getMaximumResolution = function() { return ownerMap.zoom };
	   G_HYBRID_MAP.getMaximumResolution = function() { return ownerMap.zoom };
	}
	
	if (ownerMap.showMarker)
	{
		var propIcon = new GIcon(G_DEFAULT_ICON);
		propIcon.image = ownerMap.rootPath + "/images/green-dot.png";
		propIcon.shadow = ownerMap.rootPath + "/images/shadow50.png";
		propIcon.iconSize = new GSize(32, 32);
		propIcon.shadowSize = new GSize(59, 32);
		propIcon.iconAnchor = new GPoint(16, 29);
		propIcon.infoWindowAnchor = new GPoint(16, 1);

		var latLng = new GLatLng(ownerMap.lat, ownerMap.lng);
		OwnerMaps_HomeMarker = new GMarker(latLng, { title: "", draggable: false, icon: propIcon });
		map.addOverlay(OwnerMaps_HomeMarker);
		GEvent.bind(OwnerMaps_HomeMarker, "click", this, function()
		{
			ShowInfoBubble("HomeMarker");
		});
	}
	
	if (ownerPOIs && ownerPOIs.length > 0)
	{
		var x;
		var i = 0;
		for (x in ownerPOIs)
		{
			var letter = String.fromCharCode("A".charCodeAt(0) + i);
			var TheIcon = new GIcon();
			TheIcon.image = ownerMap.rootPath + "/images/marker" + letter + ".png";
			TheIcon.shadow = ownerMap.rootPath + "/images/shadow50.png";
			TheIcon.iconSize = new GSize(20, 34);
			TheIcon.shadowSize = new GSize(34, 37);
			TheIcon.iconAnchor = new GPoint(16, 29);
			TheIcon.infoWindowAnchor = new GPoint(16, 1);

			var vals = ownerPOIs[x].split(","); //values look like "lat,long,title,desc"
			var posn = new GLatLng(vals[0], vals[1]);
			var geoMarker = new GMarker(posn, { title: "", draggable: false, icon: TheIcon })
			geoMarker.Title = unescape(vals[2]);
			geoMarker.Desc = unescape(vals[3]);
			geoMarker.Letter = letter;
			GEvent.addListener(geoMarker, "click", function() 
			{
				this.openInfoWindowHtml(GetBubbleHtml(this));
			});
			map.addOverlay(geoMarker);
			OwnerMaps_MapList[i] = geoMarker;
			i++;
		}
	}

	// Keep track of map change events so that the cookie can be updated.
	GEvent.addListener(map, "maptypechanged", MapTypeChanged);
}

var mapTypeCookieName = "MapType";

// Set the map type based on the cookie value.
function SetMapType()
{
	var mapTypeString = getCookie(mapTypeCookieName);

	if (mapTypeString == "G_NORMAL_MAP")
	{
		map.setMapType(G_NORMAL_MAP);
	}
	else if (mapTypeString == "G_SATELLITE_MAP")
	{
		map.setMapType(G_SATELLITE_MAP);
	}
	else if (mapTypeString == "G_HYBRID_MAP")
	{
		map.setMapType(G_HYBRID_MAP);
	}
}

// Persist the map type to the cookie.
function WriteMapTypeCookie()
{
	var mapType = map.getCurrentMapType();
	var mapTypeString = "G_NORMAL_MAP";

	if (mapType == G_SATELLITE_MAP)
	{
		mapTypeString = "G_SATELLITE_MAP";
	}
	else if (mapType == G_HYBRID_MAP)
	{
		mapTypeString = "G_HYBRID_MAP";
	}


	var expires = new Date();
	expires.setFullYear(expires.getFullYear() + 1);

	setCookie(mapTypeCookieName, mapTypeString, expires, false, false, false);
}

function MapTypeChanged()
{
	WriteMapTypeCookie();
}

function GetBubbleHtml(marker)
{
  	var html = "<div class='InfoTitleNoEdit'>" + PrepareForDisplay(marker.Title) + "</div>";
  	html += "<div class='InfoDescNoEdit'>" + PrepareForDisplay(marker.Desc) + "</div>";
  	return html;
}

function PrepareForDisplay(strIn)
{
	var strOut = unescape(strIn);
	strOut = encodeMyHtml(strOut);
	strOut = FixCommas(strOut);
	return strOut;
}

function FixCommas(strIn)
{
	return strIn.replace(/{{COMMA}}/g, ",");
}

function FixBreakingSpace(strIn)
{
	var strOut = strIn.replace(/\r/g, "");
	strOut = strOut.replace(/\n/g, "<br/>");
	strOut = strOut.replace(/ /g, "&nbsp;");
	return strOut;
}

function encodeMyHtml(strIn) 
{
	var strOut = strIn;
	strOut = strOut.replace(/</g,"&lt;");
	strOut = strOut.replace(/>/g,"&gt;");
	return strOut;
}

function loadMaps() {
	$(window).unload( function() {
		if(typeof GUnload != 'undefined') GUnload();
	});
	google.load("maps", "2", {"callback" : mapsLoaded});
}
function initLoader(_callback) {
	var script = document.createElement("script");

	// Need to specify a client id if we're https.
	var searchResult = ownerMap.gurlp.indexOf("https://");

	var client = "";

	if (searchResult == 0)
	{
		client = "&client=" + ownerMap.gcid;
	}

	script.src = ownerMap.gurlp + "/jsapi?key=" + ownerMap.gkey + "&callback=loadMaps" + client;

	script.type = "text/javascript";
	$(script).appendTo('body:first');
}

// Owner profile global vars
var poi_descs = new Array();
var toppoi_descs = new Array();
var toppoi_descs_i = 0;
var expandtext;
var expandh = 71;
var expandDetails = function(){
	var ele = $(this);
	var pid = ele.parent().prev();
	var i = ele.attr('pos');
	if(!expandtext) expandtext = ele.html();
	if(ele.html()==expandtext){ // show
		pid.animate( { height: window.poi_descs[i] }, {queue:false, duration:300 } );
		pid.addClass('poi-desc-open');
		ele.html('Collapse');
		ele.addClass('poi-colapse'); 
	}else{ // close
		pid.animate( { height:expandh }, {queue:false, duration:300 } );
		pid.removeClass('poi-desc-open');
		ele.html(expandtext); 
		ele.removeClass('poi-colapse'); 
	}
	return false;

};


function trace(str){
	if($('#debug')) $('#debug').append(str + '<br/>');
	}

/* ie6 fix (can't use jQuery animate function) */
var ie6anim = {id: null, ele: null, newh: 0, incr: 1};
function ie6animate_loop(){
	var obj = ie6anim;
	var h = obj.ele.height();
	if(obj.incr>0){
		if(h<obj.newh)return obj.ele.height(h+obj.incr);
		trace('hey'); 
		}
	else if(h>obj.newh) return obj.ele.height(h+obj.incr);
	obj.ele.height(obj.newh);
	clearInterval(obj.id); 
	obj.id = null;
	}
function ie6animate(ele, newh){
	var obj = ie6anim;
	obj.ele = ele;
	obj.newh = newh;
	var h = ele.height();
	if(h<newh) obj.incr = 1;
	else if(h>newh)obj.incr = -1;
	else return; // no need
	if(!obj.id)obj.id = setInterval('ie6animate_loop()', 500);
}
	
$(function() {
    $('a.calendar').click(function() {
        var pid = $(this).attr('rel');
        $("div.calendar-target").load("/Listing/CalendarData.aspx?listing=" + pid, null, function() {
            $('#calendar-overlay').gtmodal({
                buttons: []
            });
        });
	if (typeof ViewCalendarOnClick == 'function') {
            ViewCalendarOnClick();
        }
        return false;
    });
});

// using jQuery's ready event

$(function() {
	$('a.calendar').show();
	//see if user wants to go directly to calendar
	var url = document.location.toString();
	if (url.match("#calendar")) {
		$('#btnCalendar1').click();
	}
	if ($("#mastheadAd").length) $("#mastheadAd").attr("src", $("#mastheadSrc").attr("value"));
	if ($("#listingAdIFrame").length) $("#listingAdIFrame").attr("src", $("#listingAdSrc").attr("value"));

	if ($('#inReviewMode').val() == "True") {
		//disable all links except calendar when in review mode 
		$("a:not(.calendar)").bind("click", function() { return false; });
		if ($('#inMasterAdminMode').val() == "True") {
			$("a.calendar").unbind('click').get(0).removeAttribute('onclick');
		}
	}
	if ($('#expiredListing').val() == "True") {
		//disable intra-page navigation. there shouldn't be any other links showing in the listing content.
		$('.page-bar li a').click(function() { return false; }).attr('href', '');
		$('#currencyLink').click(function() { return false; }).attr('href', '');
	}
	//Check to see if we need init the google map for this listing
	if (typeof ownerMap != 'undefined') {
		initLoader();
	} //End GMap if




	//Check to see if we have an owner profile
	if ($('#locationWrapper').length != 0) {


		var isie6 = ($.browser.msie && ($.browser.version < 7));

		// activation
		$('#OwnProf').addClass('jsactive');
		$('#OwnProfReadMoreBar').addClass('jsactive');
		var anchorpos = 0;
		$('a.poi-readmore').each(function(id, Obj) {
			$(Obj).addClass('poi-readmore-jsactive');
			$(Obj).click(expandDetails);
			$(Obj).attr('pos', anchorpos++);
		});

		var OwnPhoto = $('.OwnPhoto');
		var OwnImg = $(document.createElement('img'));
		OwnImg.addClass('OwnImg');
		var str = String(OwnPhoto.css('background-image'));
		var imgurl = $.browser.msie ? str.slice(5, -2) : str.slice(4, -1);
		OwnImg.attr('src', imgurl);
		OwnPhoto.append(OwnImg);

		//turn on home marker if needed
		if (typeof ownerMap != 'undefined' && ownerMap.showMarker) {
			$(".SListHeader").attr("class", "SListHeader ShowMarker");
		}

		// open/close MAIN DESCRIPTION

		var closehtml = 'Collapse';
		var padding = 50;
		var h = $('#OwnProfDesc').height();
		var lefth = $('#POIList').height();
		var origh = $('#OwnProf').height();
		if (isie6) {
			origh = 130;
			padding = 60;
			lefth += 10;
		}
		var dif = h + padding - origh;

		if (h < 85) { $('#OwnProfReadMore').hide(); }
		else { // origh
			h += padding;
			var ReadMore = $('#OwnProfReadMore');
			var orightml = ReadMore.html();

			ReadMore.show();
			ReadMore.click(function() {
				if ($(this).html() == closehtml) { // close
					if (isie6) {
						$("#OwnProf").height(origh);
						$("#POIList").height(lefth);
					}
					else {
						$("#OwnProf").animate({ height: origh }, { queue: false, duration: 300 });
						$("#POIList").animate({ height: lefth }, { queue: false, duration: 300 });
					}

					$(this).html(orightml);
					$('#OwnProfReadMoreBar').removeClass('readmoreopen');
					$('#OwnProfReadMoreBar2').removeClass('rmopen');
				} else { // open
					if (isie6) {
						$("#OwnProf").height(h);
						$("#POIList").height(lefth + dif);
					}
					else {
						$("#OwnProf").animate({ height: h }, { queue: false, duration: 300 });
						$("#POIList").animate({ height: (lefth + dif) }, { queue: false, duration: 300 });
					}

					$(this).html(closehtml);
					$('#OwnProfReadMoreBar').addClass('readmoreopen');
					$('#OwnProfReadMoreBar2').addClass('rmopen');
				}
				return false
			});
		}



		// open/close POI DESCRIPTIONS
		var smallheight = 70;
		$('.poi-readmore').each(function(id, obj) {
			var desc = $('#poi-desc-' + id);
			var h = desc.height();
			poi_descs[id] = h;
			if (h < (smallheight + 5)) $(this).hide();
			else desc.addClass('poi-hider');
		});

		// open/close TOP POI (override)
		var readmore = 'Read more';
		var collapse = 'Collapse';
		$('#POIList .shortPara').each(function() {

			var Para = $(this);
			var ppos = toppoi_descs_i++;
			var parah = Para.height();
			toppoi_descs.push(parah);
			if (parah < (smallheight + 5)) return; // ignore
			var Div = $(document.createElement('div')).html(Para.html());
			Para.html(Div);
			Div.addClass('shortParaInner');
			Div.animate({ height: smallheight }, { queue: false, duration: 300 });

			// readmore button
			var Button = $(document.createElement('a')).html(readmore);
			Button.attr('href', '#');
			Button.addClass('shortParaLink');
			Button.click(function() {
				var ThisObj = $(this);
				var ShortDiv = ThisObj.prev();

				if (ThisObj.html() == collapse) { // close
					ShortDiv.animate({ height: smallheight }, { queue: false, duration: 300 });
					ThisObj.html(readmore);
				}
				else { // open
					ShortDiv.animate({ height: toppoi_descs[ppos] }, { queue: false, duration: 300 });
					ThisObj.html(collapse);
				}

				return false;
			});

			Para.append(Button);
		});

	}

	if ($.browser.msie && ($.browser.version > 6)) {
		window.onbeforeprint = function() {
			$('#ieprint').html($('#OwnProfDesc').html());
			$('#ieprint').show();
			$('#OwnProfDesc').hide();


			/* IE7 print gallery fix START */
			if (!haspg) {
				var pgallery = $("<div class='printgallery'></div>");
				$('.gallery').after(pgallery);

				var i = 0;
				var j = 0;
				$('.gallery img').each(function() {
					var div2 = $("<div></div>").css({ float: 'left' });
					div2.attr('id', 'printgallery-' + (j++));
					var img = $("<img />");
					img.attr('src', $(this).attr('src'));
					div2.append(img);
					pgallery.append(div2);
					if (i++) {
						i = 0;
						pgallery.append($("<div></div>").css({ clear: 'both', width: 'auto' }));
						var newdiv = $("<div class='printgallery'></div>");
						pgallery.after(newdiv);
						pgallery = newdiv;
					}
				});

				i = 0;
				$('.gallery dl dd').each(function() {
					$("#printgallery-" + i++).append("<br/>").append($(this).html());
				});
				haspg = true;
			}
			else $(".printgallery").show();
			/* IE7 print gallery fix END */



		}
		window.onafterprint = function() {
			$('#ieprint').hide();
			$('#OwnProfDesc').show();

			// IE7 print gallery fix END 
			$('.printgallery').hide();
		}

	}



});

var haspg = false;

function Trim(text) {
    return text.replace(/^[\s]+/, '').replace(/[\s]+$/, '');
}

function InquiryConstants() {
}

// Constants:
InquiryConstants.prototype.cookieName = 'Trip';
InquiryConstants.prototype.fieldName = 'AcceptedEmailWithWarnings';
InquiryConstants.prototype.noEmailAddress = 'none';
InquiryConstants.prototype.emailOrPhoneRequired = 'Either a Phone number OR an Email address is required to send an Inquiry.';
InquiryConstants.prototype.pleaseEnterEmailAddress = 'Please enter a value for the "Email Address" field.';
InquiryConstants.prototype.enterFullName = 'Enter a value for the "Full Name" field.';
InquiryConstants.prototype.emailsDoNotMatch = 'Email addresses do not match. Please ensure that Email Address and Confirmation Email Address are the same.';
InquiryConstants.prototype.correctAndReSubmit = 'Please correct the following errors and re-submit:';
InquiryConstants.prototype.warningsFound = 'Warning(s) found, please correct prior to resending - if you are 100% sure that the email address entered is correct, please press "Send Email Now" button again.';

var inquiryConstants = new InquiryConstants();

function DisplayInquiryErrorsAndWarnings(bulletListItems, errorLabel, scrollTo) {
    var html = bulletListItems[0];

    if (bulletListItems.length > 1) {
        html += "<ul>";
        
        for (var i = 1; i < bulletListItems.length; i++) {
            html += '<li>' + bulletListItems[i] + '</li>';
        }
        
        html += "</ul>";
    }

    errorLabel.html(html);

    // Scroll to top of error message.
    if (scrollTo != null) {
        window.scrollTo(0, scrollTo.offset().top);
    }
}

// Save the email that the user was just warned about in the Trip cookie.
function SaveWarnEmailAddress(emailAddress) {
    var fieldValue = escape(emailAddress);
    var tripCookie = $.cookie(inquiryConstants.cookieName);
    var expiration = 30; // days
    
    if (tripCookie == null) {
        $.cookie(inquiryConstants.cookieName, inquiryConstants.fieldName + '=' + fieldValue, { path: '/', expires: expiration });
    }
    else {
        var cookieValue = $.cookie(inquiryConstants.cookieName);

        if (cookieValue.indexOf(inquiryConstants.fieldName) == -1) {
            $.cookie(inquiryConstants.cookieName, cookieValue + "&" + inquiryConstants.fieldName + "=" + fieldValue, { path: '/', expires: expiration });
        }
        else {
            var newCookieValue = cookieValue.replace(/AcceptedEmailWithWarnings[^&]+/, inquiryConstants.fieldName + "=" + fieldValue)
            $.cookie(inquiryConstants.cookieName, newCookieValue, { path: '/', expires: expiration });
        }
    }
}

// Retrieve email address about which the user was previously warned from the Trip cookie.
function GetWarnEmailAddress() {
    var emailAddress = "";
    
    var fullCookieValue = $.cookie(inquiryConstants.cookieName);

    if (fullCookieValue != null) {
        var matchResult = fullCookieValue.match(/AcceptedEmailWithWarnings[^&]+/);

        if (matchResult != null) {
            var equalPos = matchResult[0].indexOf('=');
            
            if (equalPos != -1) {
                emailAddress = matchResult[0].substring(equalPos + 1);
            }
        }
    }
    
    return unescape(emailAddress);
}

function CopyMessages(messages, bulletListItems) {
    for (var i = 0; messages != null && i < messages.length; i++) {
        bulletListItems[bulletListItems.length] = messages[i];
    }
}

/* Do inquiry validations, and if successful, copy the field values to the original inquiry form. */
function CalloutInquiryValidateAndCopy($context) {
    var isValid = true;
    var errors = false;
    var warnings = false;
    var $context = $context || null;

    var errorLabel = $('label[id=coErrorLabel]', $context);

    var haveWarningsOrErrors = errorLabel != null && errorLabel.text().length > 0;

    // Clear error message text.
    errorLabel = $('label[id=coErrorLabel]', $context);
    errorLabel.text('');

    var fullName = Trim($('input[name=coFullName]', $context).val());
    var phone = Trim($('input[name=coHomePhone]', $context).val());
    var emailAddress = Trim($('input[name=coEmailAddress]', $context).val().toLowerCase());
    var reEnterEmailAddress = Trim($('input[name=coReEnterEmailAddress]', $context).val().toLowerCase());

    var userEnteredNone = false;
    
    if (emailAddress == inquiryConstants.noEmailAddress) {
        emailAddress = '';
        userEnteredNone = true;
    }

    if (reEnterEmailAddress == inquiryConstants.noEmailAddress) {
        reEnterEmailAddress = '';
    }
    
    var bulletListItems = new Array();

    if (fullName.length == 0) {
        bulletListItems[bulletListItems.length] = inquiryConstants.enterFullName;
        isValid = false;
        errors = true;
    }

    var emailOrPhoneRequired = false;
    
    if (fullName.length > 0 && userEnteredNone && reEnterEmailAddress.length == 0 && phone.length == 0) {
        bulletListItems[bulletListItems.length] = inquiryConstants.emailOrPhoneRequired;
        isValid = false;
        errors = true;
        emailOrPhoneRequired = true;
    }

    if (!emailOrPhoneRequired && emailAddress.length == 0 && (phone.length == 0 || fullName.length == 0)) {
        bulletListItems[bulletListItems.length] = inquiryConstants.pleaseEnterEmailAddress;
        isValid = false;
        errors = true;
    }

    if (emailAddress != reEnterEmailAddress) {
        bulletListItems[bulletListItems.length] = inquiryConstants.emailsDoNotMatch;
        isValid = false;
        errors = true;
    }

    if (emailAddress.length > 0 && emailAddress == reEnterEmailAddress) {
        var validationResult = ValidateEmailAddress(emailAddress);

        if (validationResult.Status == EmailAddressValidationStatus.Errors) {
            isValid = false;
            errors = true;
            CopyMessages(validationResult.Messages, bulletListItems);
        }
        else if (validationResult.Status == EmailAddressValidationStatus.Warnings) {
            // Warn the user only if he wasn't previously warned.
            if (GetWarnEmailAddress() != emailAddress) {
                warnings = true;

                CopyMessages(validationResult.Messages, bulletListItems);
            }
        }
    }

    if (isValid && !warnings) {
        CopyFieldValues($context);
    }
    else {
        if (errors) {
            bulletListItems.unshift(inquiryConstants.correctAndReSubmit);
        }
        else {
            bulletListItems.unshift(inquiryConstants.warningsFound);
        }

        if (haveWarningsOrErrors) {
            // If an error is already displayed, need to make it invisible, update it with new content, and make it visible so the user sees that something happened.

            // DO NOT DISPLAY WARNINGS IF THE USER WAS PREVIOUSLY WARNED.
            if (errors || (warnings && emailAddress != GetWarnEmailAddress())) {
                setTimeout(function() { DisplayInquiryErrorsAndWarnings(bulletListItems, errorLabel, null); }, 500);
            }
        }
        else {
            DisplayInquiryErrorsAndWarnings(bulletListItems, errorLabel, null);
        }
    }

    if (warnings) {
        // If user is being warned the first time about invalid fields, display a warning message and do not submit the inquiry.
        // If the user is resubmitting after getting a warning, and has not changed any validated field, submit the inquiry.
        if (emailAddress != GetWarnEmailAddress()) {
            isValid = false;
            SaveWarnEmailAddress(emailAddress);
        }
    }

    if (isValid) {
        CopyFieldValuesToListingPage($context);
    }

    return isValid;
}

/* Copy the value from the source field to the destination field */
function CopyFieldValue(destinationFieldSelector, sourceFieldSelector, rev) {
    if (rev) {
        var sourceFieldValue = $(destinationFieldSelector).val();
        sourceFieldSelector.each(function() {
            $(this)[0].setAttribute('value', sourceFieldValue);
        });
    } else {
        var sourceFieldValue = $(sourceFieldSelector).val();
        $(destinationFieldSelector).val(sourceFieldValue);
    }
}

/* Copy all field values from the callout to the original inquiry form */
function CopyFieldValues($context) {
    /* This code will need to change when we change to Promise inquiries */
    var $context = $context || null;

    CopyFieldValue('#ctl00_bodyContent_InquireFormPrevControl_fullName', $('input[name=coFullName]', $context));
    CopyFieldValue('#ctl00_bodyContent_InquireFormPrevControl_emailAddress', $('input[name=coEmailAddress]', $context));
    CopyFieldValue('#ctl00_bodyContent_InquireFormPrevControl_reEnterEmailAddress', $('input[name=coReEnterEmailAddress]', $context));
    CopyFieldValue('#ctl00_bodyContent_InquireFormPrevControl_homePhone', $('input[name=coHomePhone]', $context));
    CopyFieldValue('#ctl00_bodyContent_InquireFormPrevControl_desiredArrivalDate', $('input[name=coDesiredArrivalDate]', $context));
    CopyFieldValue('#ctl00_bodyContent_InquireFormPrevControl_lengthOfStay', $('input[name=coLengthOfStay]', $context));
    CopyFieldValue('#ctl00_bodyContent_InquireFormPrevControl_numberInParty', $('input[name=coNumberInParty]', $context));
    CopyFieldValue('#ctl00_bodyContent_InquireFormPrevControl_Comments', $('textarea[name=coComments]', $context));
}

function LoadFieldValues($context) {
    /* This code will need to change when we change to Promise inquiries */
    var $context = $context || null;

    CopyFieldValue('#ctl00_bodyContent_InquireFormPrevControl_fullName', $('input[name=coFullName]', $context), true);
    CopyFieldValue('#ctl00_bodyContent_InquireFormPrevControl_emailAddress', $('input[name=coEmailAddress]', $context), true);
    CopyFieldValue('#ctl00_bodyContent_InquireFormPrevControl_reEnterEmailAddress', $('input[name=coReEnterEmailAddress]', $context), true);
    CopyFieldValue('#ctl00_bodyContent_InquireFormPrevControl_homePhone', $('input[name=coHomePhone]', $context), true);
    CopyFieldValue('#ctl00_bodyContent_InquireFormPrevControl_desiredArrivalDate', $('input[name=coDesiredArrivalDate]', $context), true);
    CopyFieldValue('#ctl00_bodyContent_InquireFormPrevControl_lengthOfStay', $('input[name=coLengthOfStay]', $context), true);
    CopyFieldValue('#ctl00_bodyContent_InquireFormPrevControl_numberInParty', $('input[name=coNumberInParty]', $context), true);

    $('textarea[name=coComments]').text($('#ctl00_bodyContent_InquireFormPrevControl_Comments').val());
    
    if ($('#ctl00_bodyContent_InquireFormPrevControl_saveForInquiries', $context).get(0).checked) bCheck = true;
    else bCheck = false;

    $('input[name=coSaveForInquiries]', $context).each(function() {
        var $t = $(this).get(0);
        $t.removeAttribute('checked');
        if (bCheck) {
            $t.setAttribute('checked', bCheck);
            $t.checked = bCheck;
        }
    });

    if ($('#ctl00_bodyContent_InquireFormPrevControl_getNews', $context).get(0).checked) bCheck = true;
    else bCheck = false;

    $('input[name=coGetNews]', $context).each(function() {
        var $t = $(this).get(0);
        $t.removeAttribute('checked');
        if (bCheck) {
            $t.setAttribute('checked', bCheck);
            $t.checked = bCheck;
        }
    });
}

function CopyFieldValuesToListingPage($context) {
    $('#ctl00_bodyContent_InquireFormPrevControl_fullName').val($('input[name=coFullName]', $context).val());
    $('#ctl00_bodyContent_InquireFormPrevControl_emailAddress').val($('input[name=coEmailAddress]', $context).val());
    $('#ctl00_bodyContent_InquireFormPrevControl_reEnterEmailAddress').val($('input[name=coReEnterEmailAddress]', $context).val());
    $('#ctl00_bodyContent_InquireFormPrevControl_homePhone').val($('input[name=coHomePhone]', $context).val());
    $('#ctl00_bodyContent_InquireFormPrevControl_desiredArrivalDate').val($('input[name=coDesiredArrivalDate]', $context).val());
    $('#ctl00_bodyContent_InquireFormPrevControl_lengthOfStay').val($('input[name=coLengthOfStay]', $context).val());
    $('#ctl00_bodyContent_InquireFormPrevControl_numberInParty').val($('input[name=coNumberInParty]', $context).val());
    $('#ctl00_bodyContent_InquireFormPrevControl_Comments').val($('textarea[name=coComments]', $context).val());

    // Checkboxes.
    var checkState = $('input[name=coSaveForInquiries]', $context).attr('checked');
    $('#ctl00_bodyContent_InquireFormPrevControl_saveForInquiries').attr('checked', checkState);
    $('#ctl00_bodyContent_InquireFormPrevControl_saveForInquiries').checked = checkState;

    var checkState = $('input[name=coGetNews]', $context).attr('checked');
    $('#ctl00_bodyContent_InquireFormPrevControl_getNews').attr('checked', checkState);
    $('#ctl00_bodyContent_InquireFormPrevControl_getNews').checked = checkState;
}

// Validate the inquiry fields on the listing page.
function ListingPageInquiryValidate() {
    var isValid = true;

    var fullName = Trim($('#ctl00_bodyContent_InquireFormPrevControl_fullName').val());
    var phone = Trim($('#ctl00_bodyContent_InquireFormPrevControl_homePhone').val());
    var emailAddress = Trim($('#ctl00_bodyContent_InquireFormPrevControl_emailAddress').val().toLowerCase());
    var reEnterEmailAddress = Trim($('#ctl00_bodyContent_InquireFormPrevControl_reEnterEmailAddress').val().toLowerCase());
    var errorLabel = $('#csErrDiv');

    var userEnteredNone = false;

    if (emailAddress == inquiryConstants.noEmailAddress) {
        userEnteredNone = true;
        emailAddress = '';
    }

    if (reEnterEmailAddress == inquiryConstants.noEmailAddress) {
        reEnterEmailAddress = '';
    }

    var previousErrorsOrWarnings = errorLabel.text().length > 0;
    
    errorLabel.text('');

    var warnings = false;
    var errors = false;
    var bulletListItems = new Array();

    if (fullName.length == 0) {
        bulletListItems[bulletListItems.length] = inquiryConstants.enterFullName;
        errors = true;
        isValid = false;
    }

    var emailOrPhoneRequired = false;

    if (fullName.length > 0 && userEnteredNone && reEnterEmailAddress.length == 0 && phone.length == 0) {
        bulletListItems[bulletListItems.length] = inquiryConstants.emailOrPhoneRequired;
        isValid = false;
        errors = true;
        emailOrPhoneRequired = true;
    }

    if (!emailOrPhoneRequired && emailAddress.length == 0 && (phone.length == 0 || fullName.length == 0) && !userEnteredNone) {
        bulletListItems[bulletListItems.length] = inquiryConstants.pleaseEnterEmailAddress;
        errors = true;
        isValid = false;
    }

    if (emailAddress != reEnterEmailAddress) {
        bulletListItems[bulletListItems.length] = inquiryConstants.emailsDoNotMatch;
        errors = true;
        isValid = false;
    }

    if (emailAddress.length > 0 && emailAddress == reEnterEmailAddress) {
        var validationResult = ValidateEmailAddress(emailAddress);

        if (validationResult.Status == EmailAddressValidationStatus.Errors) {
            errors = true;
            isValid = false;
            
            CopyMessages(validationResult.Messages, bulletListItems);
        }
        else if (validationResult.Status == EmailAddressValidationStatus.Warnings) {
            // Warn the user only if he wasn't previously warned.
            if (GetWarnEmailAddress() != emailAddress) {
                warnings = true;

                CopyMessages(validationResult.Messages, bulletListItems);
            }
        }
    }

    if (warnings) {
        // Return invalid if the user has not been previously warned about the current email address.
        if (GetWarnEmailAddress() != emailAddress) {
            isValid = false;
        }

        SaveWarnEmailAddress(emailAddress);
    }

    if (!isValid) {
        if (errors) {
            bulletListItems.unshift(inquiryConstants.correctAndReSubmit);
        }
        else {
            bulletListItems.unshift(inquiryConstants.warningsFound);
        }
    }

    if (!isValid) {
        if (previousErrorsOrWarnings) {
            setTimeout(function() { DisplayInquiryErrorsAndWarnings(bulletListItems, errorLabel, errorLabel); }, 500, errorLabel);
        }
        else {
            DisplayInquiryErrorsAndWarnings(bulletListItems, errorLabel, errorLabel);
        }
    }

    return isValid;
}

/* begin email address validation */

var _emailRegex = /^("[\x01-\x7f]*"|(?:[a-zA-Z0-9!#$%&'*+-\/=?^_`{|}~])+(?:\.(?:[a-zA-Z0-9!#$%&'*+-\/=?^_`{|}~])+)*)@(?:(?:\[?(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))\.){3}(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\]?)|(?:[a-zA-Z0-9-]{1,}\.)+(?:[a-zA-Z]){2,})$/i;

var _knownTopLevelDomainsRegex = /\.(com|net|org|edu|gov|mil|biz|aero|coop|info|museum|name|pro|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cf|cg|ch|ci|ck|cl|cm|cn|co|com|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|fx|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nato|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zr|zw)$/i;

function EmailAddressValidationResult() {
    EmailAddressValidationStatus = { NoWarningsOrErrors: 0, Warnings: 1, Errors: 2 };

    this.Status = null;
    this.Messages = new Array();
    this.InferredEmailAddress = null;
}

function ValidateEmailAddress(emailAddress) {
    var result = new EmailAddressValidationResult();

    var fullEmailAddress = emailAddress;
    var extractedEmailAddress = ExtractEmailAddressInsideBrackets(emailAddress);

    result.Status = EmailAddressValidationStatus.NoWarningsOrErrors;

    result.Messages = GetEmailErrorMessages(extractedEmailAddress);

    if (result.Messages.length > 0) {
        result.Status = EmailAddressValidationStatus.Errors;
    }
    else {
        var warningMessagesResult = GetEmailWarningMessages(extractedEmailAddress, fullEmailAddress);

        if (warningMessagesResult.WarningMessages.length > 0) {
            result.Status = EmailAddressValidationStatus.Warnings;
            result.Messages = warningMessagesResult.WarningMessages;
            result.InferredEmailAddress = warningMessagesResult.InferredEmailAddress;
        }
    }

    return result;
}

function IndexOfAny(charArray, text) {
    var result = -1;

    for (var i = 0; i < charArray.length; i++) {
        var index = text.indexOf(charArray[i]);

        if (index > -1) {
            if (result == -1) {
                result = index;
            }
            else {
                result = Math.min(result, index);
            }
        }
    }

    return result;
}

function ExtractEmailAddressInsideBrackets(emailAddress) {
    var result = emailAddress;

    var bracketBeginPos = IndexOfAny(['<', '['], emailAddress);
    var bracketEndPos = IndexOfAny(['>', ']'], emailAddress);

    if (bracketBeginPos >= 0 && bracketEndPos > bracketBeginPos) {
        result = emailAddress.substr(bracketBeginPos + 1, bracketEndPos - bracketBeginPos - 1);
    }

    return result;
}

function EmailErrorMessageResult() {
    this.Error = false;
    this.ErrorMessage = null;
}

function EmailWarningMessageResult() {
    this.Warning = false;
    this.WarningMessage = null;
}

function MissingAtOrDot(emailAddress) {
    var result = new EmailErrorMessageResult();

    var atFound = emailAddress.indexOf('@') >= 0;
    var dotFound = emailAddress.indexOf('.') >= 0;

    if (!atFound || !dotFound) {
        result.Error = true;

        if (!atFound && !dotFound) {
            result.ErrorMessage = 'Email Address does not contain a "@\" or a ".".';
        }
        else if (!atFound) {
            result.ErrorMessage = 'Email Address does not contain a "@".';
        }
        else {
            result.ErrorMessage = 'Email Address does not contain a ".".';
        }
    }

    return result;
}

function TooShort(emailAddress) {
    var result = new EmailErrorMessageResult();

    var minLength = 5;

    if (emailAddress.length < minLength) {
        result.Error = true;
        result.ErrorMessage = "Address is not long enough.";
    }

    return result;
}

function ValidatePeriods(emailAddress) {
    var result = new EmailErrorMessageResult();

    var localPart = GetLocalPart(emailAddress);

    if (localPart != null && localPart.length > 0) {
        if (localPart.indexOf("..") != -1) {
            result.Error = true;
            result.ErrorMessage = "Address must not contain two or more consecutive periods ('.').";
        }
        else if (localPart[0] == '.') {
            result.Error = true;
            result.ErrorMessage = "Address must not start with a period ('.').";
        }
        else if (localPart[localPart.length - 1] == '.') {
            result.Error = true;
            result.ErrorMessage = "Address must not have a period ('.') immediately before the at sign ('@').";
        }
    }

    return result;
}

function DotNotAfterAt(emailAddress) {
    var result = new EmailErrorMessageResult();

    var atIndex = emailAddress.indexOf('@');
    var dotIndex = emailAddress.lastIndexOf('.');

    if (atIndex >= 0 && dotIndex >= 0 && atIndex > dotIndex) {
        result.Error = true;
        result.ErrorMessage = "There must be a \".\" somewhere following the \"@\".";
    }

    return result;
}

function GetLocalPart(emailAddress) {
    var result = null;

    var atIndex = emailAddress.indexOf('@');

    if (atIndex >= 0) {
        result = emailAddress.substring(0, atIndex);
    }

    return result;
}

function LocalPartIsQuoted(emailAddress) {
    var result = false;

    var localPart = GetLocalPart(emailAddress);

    if (localPart != null && localPart.length >= 2 && localPart[0] == '"' && localPart[localPart.length - 1] == '"') {
        result = true;
    }

    return result;
}

function ContainsSpacesOutsideOfQuotedLocalPart(emailAddress) {
    var result = new EmailErrorMessageResult();

    var stringToInspect = emailAddress;

    if (LocalPartIsQuoted(emailAddress)) {
        var atIndex = emailAddress.indexOf('@');

        if (atIndex >= 0) {
            stringToInspect = emailAddress.substring(atIndex + 1);
        }
    }

    if (stringToInspect.indexOf(' ') >= 0) {
        result.Error = true;
        result.ErrorMessage = "Address must not contain any spaces.";
    }

    return result;
}

function ContainsCommas(emailAddress) {
    var result = new EmailErrorMessageResult();

    if (emailAddress.indexOf(',') >= 0) {
        result.Error = true;
        result.ErrorMessage = "Email Address cannot contain a comma.";
    }

    return result;
}

function SurroundedByQuotesOrDoubleQuotes(emailAddress) {
    var result = new EmailErrorMessageResult();

    if (emailAddress.length >= 2 && ((emailAddress[0] == '"' || emailAddress[0] == '\'') && (emailAddress[emailAddress.length - 1] == '"' || emailAddress[emailAddress.length - 1] == '\''))) {
        result.Error = true;
        result.ErrorMessage = "Email Address cannot be surrounded by \" or ' characters.";
    }

    return result;
}

function ContainsQuotesButLocalPartNotQuoted(emailAddress) {
    var result = new EmailErrorMessageResult();

    if (!LocalPartIsQuoted(emailAddress) && emailAddress.indexOf('"') >= 0) {
        result.Error = true;
        result.ErrorMessage = "Email Address cannot contain \" characters.";
    }

    return result;
}

function ContainsNonAsciiCharsInLocalPart(emailAddress) {
    var result = new EmailErrorMessageResult();

    var localPart = GetLocalPart(emailAddress);

    if (localPart != null) {
        for (var i = 0; !result.Error && i < localPart.length; i++) {
            if (localPart[i] >= '\u0080') {
                result.Error = true;
                result.ErrorMessage = "Address contains invalid character(s).";
            }
        }
    }

    return result;
}

function FailsRegexTest(emailAddress) {
    var result = new EmailErrorMessageResult();

    if (_emailRegex.exec(emailAddress) == null) {
        result.Error = true;
        result.ErrorMessage = "Invalid Email Address.";
    }

    return result;
}

function GetEmailErrorMessages(emailAddress) {
    // Create an array of delegates to e-mail validation methods.
    var validations = new Array
    (
        MissingAtOrDot,
        TooShort,
        DotNotAfterAt,
        ContainsSpacesOutsideOfQuotedLocalPart,
        ContainsCommas,
        SurroundedByQuotesOrDoubleQuotes,
        ContainsQuotesButLocalPartNotQuoted,
		ContainsNonAsciiCharsInLocalPart,
		ValidatePeriods
    );

    var errorMessages = new Array();

    // Call each validation method.
    for (var i = 0; i < validations.length; i++) {
        var validationResult = validations[i](emailAddress);

        if (validationResult.Error) {
            errorMessages[errorMessages.length] = validationResult.ErrorMessage;
        }
    }

    // Only want to check e-mail against the regular expression if no other errors were found.
    if (errorMessages.length == 0) {
        var regexTestResult = FailsRegexTest(emailAddress);

        if (regexTestResult.Error) {
            errorMessages[errorMessages.length] = regexTestResult.ErrorMessage;
        }
    }

    return errorMessages;
}

function StringsAreEqual(strA, strB, ignoreCase) {
    var result;

    if (strA == null && strB == null) {
        return true;
    }
    else if (strA == null && strB != null) {
        return false;
    }
    else if (strB == null && strA != null) {
        return false;
    }
    else if (ignoreCase) {
        return strA.toLowerCase() == strB.toLowerCase();
    }
    else {
        return strA == strB;
    }

    return result;
}

function StartsWithWWW(emailAddress) {
    var result = new EmailWarningMessageResult();

    var pattern = "www.";

    if (emailAddress.length >= pattern.length) {
        var startOfEmailAddress = emailAddress.substring(0, pattern.length);

        if (StringsAreEqual(startOfEmailAddress, pattern, true)) {
            result.Warning = true;
            result.WarningMessage = 'It is unlikely, yet possible, that an Email Address starts with "' + pattern + '" - please check.';
        }
    }

    return result;
}

function NotInTLDList(emailAddress) {
    var result = new EmailWarningMessageResult();

    if (_knownTopLevelDomainsRegex.exec(emailAddress) == null) {
        result.Warning = true;

        var lastDotIndex = emailAddress.lastIndexOf('.');

        var topLevelDomain = emailAddress.substr(lastDotIndex, emailAddress.length - lastDotIndex);

        result.WarningMessage = 'Please ensure that your Email address domain extension is correct. Found "' + topLevelDomain + '"."';
    }

    return result;
}

function ContainsSingleQuotes(emailAddress) {
    var result = new EmailWarningMessageResult();

    if (emailAddress.indexOf('\'') >= 0) {
        result.Warning = true;
        result.WarningMessage = 'Found a " ' + "' - please ensure your Email Address is correct.";
    }

    return result;
}

function LocalPartIsQuoted(emailAddress) {
    var result = false;

    var atIndex = emailAddress.indexOf('@');

    if (atIndex >= 0) {
        var localPart = emailAddress.substring(0, atIndex);

        if (localPart.length >= 2 && localPart[0] == '"' && localPart[localPart.length - 1] == '"') {
            result = true;
        }
    }

    return result;
}

function QuotedLocalPart(emailAddress) {
    var result = new EmailWarningMessageResult();

    if (LocalPartIsQuoted(emailAddress)) {
        result.Warning = true;
        result.WarningMessage = 'Found " characters - please ensure your Email Address is correct.';
    }

    return result;
}

function IncludesDisplayNameResult() {
    this.IncludesDisplayName = false;
    this.WarningMessage = null;
    this.InferredEmailAddress = null;
}

function IncludesDisplayName(fullEmailAddress) {
    var result = new IncludesDisplayNameResult();

    var extractedEmailAddress = ExtractEmailAddressInsideBrackets(fullEmailAddress);

    if (fullEmailAddress != extractedEmailAddress) {
        result.IncludesDisplayName = true;

        result.InferredEmailAddress = extractedEmailAddress;
        result.WarningMessage = "Please ensure that this Email Address is correct: " + result.InferredEmailAddress;
    }

    return result;
}

function EmailWarningMessagesResult() {
    this.WarningMessages = null;
    this.InferredEmailAddress = null;
}

function GetEmailWarningMessages(emailAddress, fullEmailAddress) {
    // Create an array of delegates to e-mail validation methods.
    var validations = new Array
    (
        StartsWithWWW,
        NotInTLDList,
        ContainsSingleQuotes,
        QuotedLocalPart
    );

    var warningMessages = new Array();

    // Call each validation method.
    for (var i = 0; i < validations.length; i++) {
        validationResult = validations[i](emailAddress);

        if (validationResult.Warning) {
            warningMessages[warningMessages.length] = validationResult.WarningMessage;
        }
    }

    var includesDisplayNameResult = IncludesDisplayName(fullEmailAddress);

    if (includesDisplayNameResult.IncludesDisplayName) {
        warningMessages[warningMessages.length] = includesDisplayNameResult.WarningMessage;
    }

    var result = new EmailWarningMessagesResult();
    result.WarningMessages = warningMessages;
    result.InferredEmailAddress = includesDisplayNameResult.InferredEmailAddress;

    return result;
}

/* end email address validation */
