var IE = document.all ? true : false;
var map;
var container;
var zoom = 6;
var centerPoint = new GLatLng(37.317752, -119.750976);
var loading = false;
var selectedProperty;
var mapBounds = loadStateBounds();
var resultCount = 0;

var baseIcon = new GIcon();
baseIcon.iconSize = new GSize(12,20);
baseIcon.iconAnchor = new GPoint(6,20);
baseIcon.infoWindowAnchor = new GPoint(6,8);
var params;
var selectedMarker;
var limit = 20;
var start = 0;
var sorton = '';
var sortor = 'ASC';
var sortid = null;
//var servicePath = wwwpath + "/services2/";


var smallIcons = 0;
if (smallIcons) {
	var baseIcon = new GIcon();
	baseIcon.iconSize = new GSize(12,20);
	baseIcon.iconAnchor = new GPoint(6,20);
	baseIcon.infoWindowAnchor = new GPoint(6,8);

	var blueIcon = (new GIcon(baseIcon, wwwpath+"flx-images/mm_20_blue.png", null, ""));
	var greenIcon = (new GIcon(baseIcon, wwwpath+"flx-images/mm_20_green.png", null, ""));
	var redIcon = (new GIcon(baseIcon, wwwpath+"flx-images/mm_20_red.png", null, ""));
	var selectedIcon = (new GIcon(baseIcon, wwwpath+"flx-images/mm_20_yellow.png", null, ""));
}
else {
	var baseIcon = new GIcon();
	baseIcon.iconSize = new GSize(20, 20);
	baseIcon.iconAnchor = new GPoint(10, 10);

	var blueIcon = new GIcon(baseIcon, wwwpath+"flx-images/icon_radar_blue.png", null, "");
	var greenIcon = new GIcon(baseIcon, wwwpath+"flx-images/icon_radar_green.png", null, "");
	var redIcon = new GIcon(baseIcon, wwwpath+"flx-images/icon_radar_red.png", null, "");
	var selectedIcon = (new GIcon(baseIcon, wwwpath+"flx-images/icon_radar_yellow.png", null, ""));
}

/*
The yellow marker which shows the selected property. This marker is overimposed on the regular marker for the given property.
*/
selectedMarker = new GMarker(new GLatLng(0,0),{icon:selectedIcon,zIndexProcess:importanceOrder});
selectedMarker.importance = 2000;

/*
function importanceOrder(). Make sure that the yellowmarker goes on top of all other markers
*/
function importanceOrder (marker,b) {
	return GOverlay.getZIndex(marker.getPoint().lat()) + marker.importance*1000000;
}

/*
function load(). Called by the window.onload handler
*/

function load() {
	doLoad();
}

/*
function doLoad(). Create the map object and add an array to it to hold the markers
*/
function doLoad() {
	//alert("2-doLoad()");
	if (true && GBrowserIsCompatible()) {
		container = document.getElementById('mapDiv');
		//alert("3-adding map");
		map = new GMap2(container, {draggableCursor:'crosshair'});
		//map.addControl(new GScaleControl());
		//map.addControl(new GLargeMapControl());
		map.addControl(new GSmallZoomControl3D());
		//map.addControl(new GMapTypeControl());

		//map.enableDoubleClickZoom(); 
		map.enableContinuousZoom();
		map.enableScrollWheelZoom();

		GEvent.addListener(map, "move", mapMove);

		map.markers = Array();
		map.markersList = Array();
		map.lastGoodCenter = centerPoint;
		//alert("4-map set");
		// If params were passed in the URL load them now and perform a search accordingly, otherwise load the map displaying California.
		params = readParams();
		if (params && params['Location']) {
			search();
		} else {
			init2();
			wRecordEvent(brokerID,'searchLoad');
		}
	}
}

function init2() {
	if (map.isLoaded()) {
		return;
	}
	map.setCenter(centerPoint, zoom);
}

function unload() {
	GUnload();
}

function search(reset) {
    if (reset) start = 0;
    if (!isValidSearch()) return searchError(); 
    
	$("#loadingMessage").fadeIn('fast');
	clearResults();
    $("table.datatable").fadeOut('fast');
    
	var fields = ['Location','MinBeds','MinBaths','MinAVM','MaxAVM','MinSF','PType'];
	var qStr = '';
	for (f in fields) {
		var obj = document.getElementById(fields[f]);
		if (obj.value) {
			qStr += '&' + fields[f] + '=' + escape(obj.value);
		}
	}
    qStr += '&Type=';
    var add_comma = false;
    var atype = $("input.atype-flt");
    for (var i=0;i<atype.length;i++) {
        if (atype[i].checked) {
            if (add_comma) qStr += ",";
            qStr += atype[i].value;
            add_comma = true;
        }
    }
//    qStr += "&PType=" + $("#pType").val();
    
    qStr += "&Limit=" + (limit + 1);
    qStr += "&Start=" + start;
    
    qStr += "&Sort1Field="+sorton;
    qStr += "&Sort1Order="+sortor;
    
	var url = serviceURL + qStr;
	getData(url,'properties');
	wRecordEvent(brokerID,'widgetRun');
}

function clearResults() {
	for (var i = 0; i < map.markers.length; i++) {
		if (map.markers[i]) {
			map.removeOverlay(map.markers[i]);
		}
	}
	map.markers = Array();
	map.markersList = Array();
	var oResultCount = document.getElementById("resultCount");
	oResultCount.innerHTML = '';
	
}

function getData(url,type) {

    $.get(url, function(xml) {
            readProperties(xml, type);
        }
   );
   
}

function readProperties(xstring, type) 
{  
    init2();
    if (type !== 'properties') return;

   	var oResultCount = $('#resultCount');
	var opps =  $(xstring).find("o");
 
    if (opps && opps.length > 0) {
        var bounds = new GLatLngBounds();
        var count = 0;
        var data = new Array();
        //alert("test v2");
        for (var i = 0; i < opps.length; i++) {
            
            if (i < limit) {
                var hv = new Object();
                var attrs = opps[i].attributes;

                for ( var n = 0; n < attrs.length ; n++) {
                    hv[attrs[n].name] = attrs[n].value ? attrs[n].value : ' ';
                }
                
                if (parseFloat(hv['lat']) == 0 || parseFloat(hv['lon']) == 0) {
                	//alert("go null lat or lon for "+hv['add']);
                    map.markers[i] = null;
                    //map.markersList[i] = null;
                    //continue;
                } else {
					var point = new GLatLng(parseFloat(hv['lat']),parseFloat(hv['lon']));
					bounds.extend(point);
					var icon = getIcon(hv['type']);
	
					var mTip = '<b>Status</b>: ' + hv['type'] + '<br><b>Street</b>: ' + hv['add'] + '<br><b>City</b>: ' + hv['city'] ;
					map.markers[i] = createMarker(point,i,icon,mTip);
					map.addOverlay(map.markers[i]);
				}
                map.markersList[i] = hv;                
                count++;
                data.push(hv);
            }
        }
        
        resultCount = count;
        map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));

        $('#listDiv').setTemplate($("#table-tpl").val());
        $('#listDiv').processTemplate(data);
        $("table.datatable").fadeIn('fast');
        $("#loadingMessage").fadeOut('fast');
        
        $('table.datatable tbody tr').hover(
            function() {$(this).addClass("row-over")},
            function() {$(this).removeClass("row-over")}
        );
        
        $('table.datatable thead th.type').click(function() {sort('type', 'Type')});
        $('table.datatable thead th.add').click(function() {sort('add', 'SiteStreetName')});
        $('table.datatable thead th.city').click(function() {sort('city', 'City')});
        $('table.datatable thead th.zip').click(function() {sort('zip', 'Zip')});
        $('table.datatable thead th.state').click(function() {sort('state', 'State')});
        $('table.datatable thead th.ptype').click(function() {sort('ptype', 'PType')});
        $('table.datatable thead th.sqft').click(function() {sort('sqft', 'SqFt')});
        $('table.datatable thead th.beds').click(function() {sort('beds', 'Beds')});
        $('table.datatable thead th.baths').click(function() {sort('baths', 'Baths')});
        $('table.datatable thead th.avm').click(function() {sort('avm', 'AVM')});
        $('table.datatable thead th.saleamt').click(function() {sort('saleamt', 'SaleAmt')});
        
        if (sortid) {
            $('table.datatable th.'+sortid).addClass('sort'+sortor);
        }
        
        buildPager(opps.length);
        oResultCount.innerHTML = 'Showing ' + count + ' results';
        
    }
    else {
        $('#listDiv').setTemplate($("#table-tpl").val());
        $('#listDiv').processTemplate(new Array());
        $("table.datatable").fadeIn('fast');
        $("#loadingMessage").fadeOut('fast');
        
        oResultCount.innerHTML = 'No results found.';
    }
	
	if (count > 0) {
		//var note = document.getElementById('zillowNote');
		//note.style.display = '';
		$('#note').css('display', 'block');
	}
	
}

function addCommas(amount)
{

    var delimiter = ","; // replace comma if desired
	var a = amount.split('.',2)
	var d = parseInt(a[1]);
	var i = parseInt(a[0]);
	if(d >= 50) { // round up cents
		i = i + 1;
	}
	if(isNaN(i)) { return ''; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	var n = new String(i);
	var a = [];
	while(n.length > 3)
	{
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) { a.unshift(n); }
	n = a.join(delimiter);
	amount = minus + n;
	return '$' + amount;
}

function getIcon(otype) {
	var icon = null;
	if (otype == 'Preforeclosure') {
		icon = greenIcon;
	}
	else if (otype == 'Auction') {
		icon = blueIcon;
	}
	else if (otype == 'Bank Owned') {
		icon = redIcon;
	}
	return icon;
}

function createMarker(point,id,mIcon,mTip) {
	var marker = new GMarker(point,{icon:mIcon});

	GEvent.addListener(marker, "click", function() {
		markerClicked('row_'+id);
	});
	GEvent.addListener(marker, "mouseover", function() {
		Tip(mTip);
	});

	return marker;
}

function rowClicked(rowID) {
	selectProperty(rowID);
}

function markerClicked(rowID) {
	selectProperty(rowID);
	var oList = document.getElementById("listDiv");
	var sRow = document.getElementById(rowID);
	var scrollDist = sRow.offsetTop - oList.scrollTop;
	var scrollStep = Math.round(scrollDist/5);
	window.setTimeout(function() {scrollList(rowID,scrollStep)},10);
}


function selectProperty(rowID) {

	if (selectedProperty) {
		var sRow = document.getElementById(selectedProperty);
		if (sRow) {
			//sRow.className = 'listRow';
            $(sRow).removeClass('listRowSelected');
			var markerId = selectedProperty.replace(/row_/,"");
			map.markers[markerId].setImage(map.markers[markerId].getIcon().image);
		}
	}
	selectedProperty = rowID;
	var sRow = document.getElementById(rowID);
	$(sRow).addClass('listRowSelected');
	var markerId = rowID.replace(/row_/,"");
	map.panTo(map.markers[markerId].getLatLng())

	if (selectedMarker) {
		map.removeOverlay(selectedMarker);
	}
	selectedMarker.setPoint(map.markers[markerId].getPoint());
	map.addOverlay(selectedMarker);

}


function scrollList(rowID,scrollStep) {
	var oList = document.getElementById("listDiv");
	var sRow = document.getElementById(rowID);

	var scrollDist = sRow.offsetTop - oList.scrollTop;
	if (Math.abs(scrollDist) > 5 && oList.scrollTop + oList.clientHeight < oList.scrollHeight) {
		var scrollStep = Math.round(scrollDist/5);
		oList.scrollTop = oList.scrollTop + scrollStep;
		window.setTimeout(function() {scrollList(rowID,scrollStep)},50);
	}
	else {
		oList.scrollTop = sRow.offsetTop;
	}
}


function showDetails(id) {
	window.setTimeout(function(){detailsForm(id)},100);
}

function detailsForm(id) {
	var oPopupDiv = document.getElementById("popupDiv");
	$('#popupDiv').fadeIn();
	
	oPopupDiv.style.left = (document.body.clientWidth / 2) - (oPopupDiv.clientWidth / 2) + 'px';

	var oPropDetailsDiv = document.getElementById("propDetailsDiv");
	var hv = map.markersList[id];

	var html = '';
	html += '<table cellspacing="0" cellpadding="0" width="100%">';
	html += '<tr>';
	html += '<td colspan="3" class="td1">Foreclosure Details</td>';
	html +=	'<td valign="top"><img src="'+wwwpath+'flx-images/icon_close.gif" onclick="cancelDetails()" alt="Close Window" style="cursor:pointer; margin-right: 2px;" align="right" height="16"   width="17"></td>';
	html += '</tr>';

	html += '<tr>';
	html += '<td class="td2">' + hv['add'] + '</td>';
	html += '<td class="td3">Type:</td>';
	html += '<td class="td3">' + hv['type'] + '</td>';
	html += '</tr>';

	html += '<tr>';
	html += '<td class="td2" rowspan="2">' + hv['city'] +', ' + hv['zip'] + '</td>';
	html += '<td class="td3"><span style="white-space: nowrap;">Est. Value</span></td>';
	html += '<td class="td3" align="left">' + addCommas(hv['AVM']) + '</td>';
	html += '</tr>';

	html += '<tr>';
	//html += '<td></td>';
	html += '<td class="td3"><span style="white-space: nowrap;">Loan Amount</span></td>';
	html += '<td class="td3" align="left">' + addCommas(hv['saleAmt']) + '</td>';
	html += '</tr>';
	html += '</table>';

	
	oPropDetailsDiv.innerHTML = html;
	wRecordEvent(brokerID,'detailsClicked ' +hv['pKey'])

}

function submitDetails() {
	var qStr = 'sendMail=1&brokerID=' + brokerID;

	var obj = document.getElementById('fName');
	if (!obj.value) {
		alert('Please enter your first name');
		return;
	}

	var obj = document.getElementById('lName');
	if (obj.value.length < 2) {
		alert('Please enter your last name');
		return;
	}
    
    
    
    if ($('#phone').val() == '' && $('#email').val() == '') {
        return alert('Please enter either valid phone or email address');
    }
    
    if ($('#phone').val() != '') {
        var obj = document.getElementById('phone');
        if (!obj.value.match(/^\(*[2-9]\d{2}\)*[- ]\d{3}[- ]\d{4}$/)) {
            alert('Please enter your phone number, complete with area code. Example: 333-444-5555');
            return;
        }
    }

    if ($('#email').val() != '') {
        var obj = document.getElementById('email');
        if (!obj.value.match(/^([\w\d\-\.]+)@{1}(([\w\d\-]{1,67})|([\w\d\-]+\.[\w\d\-]{1,67}))\.(([a-zA-Z\d]{2,4})(\.[a-zA-Z\d]{2})?)$/)) {
            alert('Please enter a valid email address');
            return;
        }
    }

	var userFields = ['fName','lName','phone','email','comments'];
	for (var v in userFields) {
		var obj = document.getElementById(userFields[v]);
		qStr += '&' + userFields[v] + '=' + obj.value;
	}

	var id = selectedProperty.replace(/row_/,"");
	var hv = map.markersList[id];
	for (var v in hv) {
		qStr += '&' + v + '=' + hv[v];
	}
	qStr += "&leadEmail=" +send_leads_to;
	qStr += "&userKey="+userKey;
	qStr += "&other="+($('#interested_in_other')[0].checked ? '1' : '0');
	var oPopup = document.getElementById('popupDiv');

	var oPopupAction = document.getElementById('popupActionDiv');
	var aHtml = '';
	aHtml += '<div class="actionMsgDiv">Sending request...</div>';
	aHtml += '<div style=""><input type="button"value="OK" onclick="$(\'#popupDiv\').fadeOut()"></div>';
	oPopupAction.innerHTML = aHtml;
	oPopupAction.style.display = '';

	GDownloadUrl('flx-includes/email-request.php', function(content,status){
		var aHtml = '';
		aHtml += '<div class="actionMsgDiv">';
		if (status == 200) {
			if (content == '<r>1</r>') {
				aHtml += 'Your request was sent. Thank you!<br>';
				aHtml += 'We will contact you shortly.<br>';
			}
			else {
				aHtml += 'An error ocurred when sending mail.';
			}
		}
		else {
			aHtml += 'Request failed. Code: ' + status;
		}
		aHtml += '</div>';
		aHtml += '<div style=""><input type="button"value="OK" onclick="cancelDetails()"></div>';
		oPopupAction.innerHTML = aHtml;
	
	},qStr);

	wRecordEvent(brokerID,'detailSubmit ' +hv['pKey'])
}

function cancelDetails() {
    $('#popupActionDiv').html('');
    $('#popupActionDiv').css('display', 'none');
	$('#popupDiv').fadeOut()
	var id = selectedProperty.replace(/row_/,"");
	var hv = map.markersList[id];
	wRecordEvent(brokerID,'detailsCancel ' +hv['pKey'])
}

/////////////////////////////////////////////////////////////////////////


/*
loadStateBounds() - Load an array of points with a rough outline of current state list
(which includes CA, OR, WA, NV, AZ).
To be used in panning restriction.
*/
function loadStateBounds() {
	var stateBounds = Array();
	stateBounds.push(new GLatLng(49.000325, -117.033110));
	stateBounds.push(new GLatLng(41.999310, -117.018268));
	stateBounds.push(new GLatLng(41.993848, -114.042009));
	stateBounds.push(new GLatLng(37.000412, -114.050533));
	stateBounds.push(new GLatLng(36.999032, -109.045086));
	stateBounds.push(new GLatLng(31.332505, -109.050043));
	stateBounds.push(new GLatLng(30.503750, -119.868880));
	stateBounds.push(new GLatLng(49.013363, -129.658612));
	return stateBounds;
}


/*
Load CA bounds for restricting panning to California
*/
function loadCABounds() {
	var californiaBounds = Array();
	californiaBounds.push(new GLatLng(42.000325, -119.994736));
	californiaBounds.push(new GLatLng(39.003711, -119.994736));
	californiaBounds.push(new GLatLng(34.477128, -113.906250));
	californiaBounds.push(new GLatLng(32.581535, -114.433594));
	californiaBounds.push(new GLatLng(32.435613, -119.245605));
	californiaBounds.push(new GLatLng(40.313043, -125.288086));
	californiaBounds.push(new GLatLng(42.081917, -125.200195));
	return californiaBounds;
}

/*
MapMoveevent handler. Restrict panning to california by checking if the center of the map is inside the CA bounds.
*/
function mapMove() {	
	var mapCenter = map.getCenter();
	var inside = InsidePolygon(mapCenter,mapBounds);
	if (inside) {
		map.lastGoodCenter = mapCenter;
	}
	else {
		map.setCenter(map.lastGoodCenter);
	}
}
//-------------- Point in polygon  --------------------------
function InsidePolygon(pt,polygon) {
	var angle = 0;
	var p1 = Array();
	var p2 = Array();
	var p = Array();

	p['h'] = pt.x;
	p['v'] = pt.y;

	var polySides = polygon.length;
	for (var i = 0 ; i < polySides; i++) {
		p1['h'] = polygon[i].x - p['h'];
		p1['v'] = polygon[i].y - p['v'];
		p2['h'] = polygon[(i+1) % polySides].x - p['h'];
		p2['v'] = polygon[(i+1) % polySides].y - p['v'];
		angle += Angle2D(p1['h'], p1['v'], p2['h'], p2['v']);
	}
	if (Math.abs(angle) < Math.PI) {
		return 0;
	}
	else {
		return 1;
	}
}


function Angle2D(x1,y1,x2,y2) {
	var dtheta;
	var theta1;
	var theta2;

	with (Math) {
		theta1 = atan2(y1,x1);
		theta2 = atan2(y2,x2);
		dtheta = theta2 - theta1;

		while (dtheta > PI) {
			dtheta -= 2*PI;
		}
		while (dtheta < -PI) {
			dtheta += 2*PI;
		}
	}
	return dtheta;
}

/*
Read params from the URL, if present and return them in an array.
*/
function readParams() {

	var qString = window.location.search;
	qString = qString.substring(1, qString.length);
	var cValues = new Array();
	var separator = '&';

	if (qString) {
		var nvPairs = qString.split(separator);
		for (var n = 0 ; n < nvPairs.length ; n++ )	{
			var nvPair = nvPairs[n];
			var nv = nvPair.split('=');
			if (typeof nv[1] != 'undefined') {
				cValues[nv[0]] = unescape(nv[1]);
			}
		}
		var fields = ['wId','Location','MinBeds','MinBaths','MinAVM','MaxAVM','MinSF','PType'];
		for (f in fields) {
			var obj = document.getElementById(fields[f]);
			if (obj && cValues[fields[f]]) {
				obj.value = cValues[fields[f]];
			}
		}
		return cValues;
	}
}


$(window).load(function() {
     $('#Location').autocomplete(wwwpath+'flx-includes/getcities.php', {maxItemsToShow:10, delay:200});    
});

function pageNext() 
{
    start += limit;
    search();
}

function pageBack() 
{
    start -= limit;
    search();
}

function buildPager(cnt)
{
    $("#pager").setTemplate($("#pager-tpl").val());
    $("#pager").processTemplate(cnt);
}

function sort(sid, fld) 
{
    if (fld == sorton) 
        sortor = (sortor == 'DESC') ? 'ASC' : 'DESC';
    else
        sortor = 'ASC';
    sorton = fld;
    sortid = sid;
    start = 0;
    search();
}

function isZipCode(code){
    var r = /^\d{5}([\-\+])*(\d{4})?$/
    var zip = code.search(r);
	return (zip == -1) ? false : true;
}

function isAlphanumeric(s)
{   
    var r = /^[a-zA-Z0-9]+$/
    return r.test(s);
}

function isAlphabetic(s)
{   
    var r = /^[a-zA-Z ]+$/
    return r.test(s);
}

function isInteger(s)
{   
    var r = /^\d+$/
    return r.test(s)
}

function hasComma(s)
{
    var r = /\,/;
    return r.test(s);
}

function isValidSearch()
{
    var s = $('#Location').val();
    if (s == 'City, ST or zip' || s == '')
        return false;
    if (isInteger(s)) {
        if (isZipCode(s))
            return true;
        return false;
    }
    if (isAlphabetic(s))
        return true;
    if (isAlphanumeric(s))
        return false;
    if (hasComma(s)) {
        return true;
    }
    
    return false;
}
function searchError()
{
    $('#Location').addClass('search_err');   
    return alert("Invalid search location. Please try again.");
}

function resetSearch()
{
    $('#Location').removeClass('search_err');
    $('#Location').val('');
}

function gotoFR(brokerID) {
	wRecordEvent(brokerID,'widgetRefer');
	window.setTimeout(function(){top.window.location = wwwpath},10);
}

function wSearch() {
	var obj = document.getElementById('Location');
	if (obj.value == 'City, ST or zip' || obj.value == '') {
		alert('Please enter a location to search');
		return;
	}

	var fields = ['wId','Location','MinBeds','MinBaths','MinAVM','MaxAVM','MinSF','Type','PType'];
	var qStr = '';
	for (f in fields) {
		var obj = document.getElementById(fields[f]);
		if (obj.value) {
			qStr += '&' + fields[f] + '=' + escape(obj.value);
		}
	}
	var url = 'flx.php?' + qStr;
	top.window.location = url;
}

function wRecordEvent(wID,ev) {
	//getData(servicePath + 'wEvents.php?wID='+wID+'&ev='+ev,'wEvent');
}

function bookmark(burl) {
    var url = getSearchUrl();

    window.open(burl + escape(url), 'bookmark');
}

function getSearchUrl()
{
    var fields = ['Location','MinBeds','MinBaths','MinAVM','MaxAVM','MinSF','PType'];
    var qStr = '';
    for (f in fields) {
            var obj = document.getElementById(fields[f]);
            if (obj.value) {
                qStr += '&' + fields[f] + '=' + escape(obj.value);
            }
    }
    qStr += '&Type=';
    var add_comma = false;
    var atype = $("input.atype-flt");
    for (var i=0;i<atype.length;i++) {
        if (atype[i].checked) {
            if (add_comma) qStr += ",";
            qStr += atype[i].value;
            add_comma = true;
        }
    }
    
//    qStr += "&PType=" + $("#pType").val();
    
    qStr += "&Limit=" + (limit + 1);
    qStr += "&Start=" + start;

    qStr += "&Sort1Field="+sorton;
    var url = wwwpath + 'flx.php?id='+ brokerID  + qStr;

    return url;
}

function emailFriend() {
  var r = /^([\w\d\-\.]+)@{1}(([\w\d\-]{1,67})|([\w\d\-]+\.[\w\d\-]{1,67}))\.(([a-zA-Z\d]{2,4})(\.[a-zA-Z\d]{2})?)$/;
  if (!r.test($('#ef_email').val())) {
     $('#ef_email').css('border','1px solid red');
     return alert('Please provide valid email');
  }
  if (!r.test($('#ef_from').val())) {
     $('#ef_from').css('border','1px solid red');
     return alert('Please provide valid "from" email');
  }

  if ($('#captcha').val() == "") {
     $('#captcha').css('border','1px solid red');
     return alert('Please type the text that appears in the image on the left');
  }


  $('#ef_email').css('border','1px solid #ccc');
  $('#ef_from').css('border','1px solid #ccc');
  $('#captcha').css('border','1px solid #ccc');
  var url = getSearchUrl();
  $.post('/flx-includes/email-friend.php',
         {'userKey':userKey,'email':$('#ef_email').val(),'message':$('#ef_message').val(),'from':$('#ef_from').val(),'search':url,'captcha':$('#captcha').val()},
         function(data) {
            if (data == '0') {
                $('#captcha').css('border','1px solid red');
                return alert('Invalid captcha. Please try again');
            }            
            $('#email-friend').fadeOut(); 
            return alert("Your email has been sent");
	 });

}

$(document).ready(function(){ load() });

