﻿var formErrors = new Array();

//log for reporting
function logSearch() {
	var frm = document.getElementById("findForm");
	var address = frm.address.value;
	var myAjax = new Ajax("/log.php?a="+address, {
		onComplete: search
	}).request();
}

//subscribe to sales - submit data to EstateSales.org
function subscribe() {
	$("#subscribeSubmit").hide();
	$("#subscribeLoading").show();
	
	$.ajax({
		url: 'http://estatesales.org/block/subscribe', 
		dataType:'jsonp',
		data:{
			email:$("#subscribeForm").find('input[name=email]').val(),
			location:$("#subscribeForm").find('input[name=address]').val(),
			radius:'25',
			source:'3'
		},
		success:function(response) {
			
			if (typeof(response.errors) == 'undefined') {
				$('#subscribeStatus').html('<b>Thank you! You will be now be notified via email of estate sales in your area.</b>')
			} else {
				errstr = '';
				for(var i = 0;i < response.errors.length;i++) {
					errstr += response.errors[i] + "<br/>";
				}
				$('#subscribeStatus').html('<p class="error">'+errstr+'</p>');
			}
			
			$("#subscribeSubmit").show();
			$("#subscribeLoading").hide();
	
		}
	});
	
}

//search for sales
function search() {
	
	var frm = document.getElementById("findForm");
	var address = frm.address.value;
	if (address == "" || address == null) {
		alert("Please enter your address including city and state and/or postal code, so we can show you sales near your area.");
		frm.address.focus();
		return;
	}
	
	lastMapAction = "search"; //variable initialized to not show noresults after user drags map
	resetMapAction = 0;
	
	//display location in case of no results
	//document.getElementById("location").innerHTML = " "+address+" ";
	var geocoder = new GClientGeocoder();
	geocoder.getLocations(address, function(response) {
	
	if (!response || response.Status.code != 200) {
		showError("searchError","Address not found. Ensure the address is complete and accurate.");
	  } else {
		//clear error message, if any
		if(document.getElementById("searchError").style.display == "block") {
			document.getElementById("searchError").innerHTML = "";
			document.getElementById("searchError").style.display = "none";
		}
		
		var place = response.Placemark[0];
		var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
		var accuracy = place.AddressDetails.Accuracy;
		//alert("accuracy: " + accuracy);
		var zoomLevel = accuracy + 8;
		//alert("zoomLevel: " + zoomLevel);
		//show subscribe to estate sales form
		var locality = address;
		if(typeof(place.AddressDetails.Country.AdministrativeArea.Locality) != 'undefined')
			locality = place.AddressDetails.Country.AdministrativeArea.Locality.LocalityName;
		else if (typeof(place.AddressDetails.Country.AdministrativeArea.PostalCode) != 'undefined')
			locality = place.AddressDetails.Country.AdministrativeArea.PostalCode.PostalCodeNumber;
		
		var myAjax = new Ajax("/subscribe.php?locality="+locality+"&address="+address, {
			//update: $('subscribe'),
			onComplete: function(response){document.getElementById('subscribe').innerHTML = response;}
		}).request();
		
		map.setCenter(point, zoomLevel);
		//if the accuracy is down to the street adddress level, lets display a "start" icon there
		//var marker = new GMarker(point);
		//map.addOverlay(marker);
		//marker.openInfoWindowHtml(address);
	  }
	});
}

var submitted = 0;
	
//validate post a sale form
function validatePost() {

	if (submitted)
		return;

	submitted = 1;
	
	f = document.getElementById("postForm");
	
	if (formErrors.length > 0) {
		//we have previous errors, lets clear them out
		for (var i = 0; i < formErrors.length; i++) {
			document.getElementById(formErrors[i].id).innerHTML = "";
			document.getElementById(formErrors[i].id).style.display = "none";
		}
		formErrors.length = 0;
	}
	
	//show loading bar
	document.getElementById("loading").style.display = "block";
	//give it 10 seconds to process, then error
	abortTimer = setTimeout("abortProcess()",15000);
	
	//check title
	if (f.postTitle.value == "") {
		formErrors[formErrors.length] = { message:"Please enter a title.", id: "titleError" };
	}

	//check address
	var myAjax = new Ajax("/geoCheck.php?address="+f.elements["postAddress"].value, {
		method: 'get',
		onComplete: checkAddressCallback
	}).request();
	
}

function abortProcess() {
	alert("Sorry, but an unexpected error occurred. Please try again later.");
	submitted = 0;
	document.getElementById("loading").style.display = "none";
}

function validateDate(e) {
	var selectedValue = e.options[e.selectedIndex].value;
	if(selectedValue=='other'){alert('In order to provide the most timely listings, we only allow sales dated within the next two weeks. Come back within 2 weeks of your sale date!');e.selectedIndex=0;return;}

	
	//validate that start date is before the end date
	if (e.name == "postEndDate") {
		var startDate = document.getElementById("postStartDate").options[document.getElementById("postStartDate").selectedIndex].value;
		startDateAsInt = parseFloat(startDate.replace(/-/g, ""));
		endDateAsInt = parseFloat(selectedValue.replace(/-/g, ""));
	} else {
		
		var endDate = document.getElementById("postEndDate").options[document.getElementById("postEndDate").selectedIndex].value;
		if (endDate == "") {
			document.getElementById("postEndDate").selectedIndex = e.selectedIndex;
			return;
		}
		startDateAsInt = parseFloat(selectedValue.replace(/-/g, ""));
		endDateAsInt = parseFloat(endDate.replace(/-/g, ""));
	}
		
	//alert(startDateAsInt+" "+endDateAsInt);
	
	if (startDateAsInt > endDateAsInt) {
		alert("Your end date cannot be before your start date.");
		e.selectedIndex = 0;
	}

}

function checkAddressCallback(stringObj, xmlObj) {
	
	var f= document.forms["postForm"];
	//validate address
	//safari comaptible method of extracting the code node value
	try {
		var bits = stringObj.split("<code>")[1];
		var code = bits.split("</code>")[0];
	} catch(e) {
		clearTimeout(abortTimer);
		alert("We apologize but due to the volume of traffic on the site we cannot process your request at this time. Everything should be back to normal in about an hour, so please try again soon!");
		//hide loading bar
		document.getElementById("loading").style.display = "none";
		return;
	}
	
	//the cleaner, but less comaptible way
	//var codeNodes = xmlObj.getElementsByTagName("code");
	//var code = codeNodes[0].firstChild.nodeValue;
	

	if (code != "200") {
		//address wasnt found
		if (!/.*addAddress.php$/.test(location.href))
			f.action = "addAddress.php";
		else
			f.action = "confirmPost.php";
		
		//formErrors[formErrors.length] = { message:"We were unable to verify this street address. Please confirm that it is accurate and try again.", id: "addressError" };
		
	} else {
		f.action = "confirmPost.php";
		//address id good, lets move on
		//check the accuracy level for 7 or greater
		var addressDetailsNodes = xmlObj.getElementsByTagName("AddressDetails");
		var accuracy = addressDetailsNodes[0].getAttribute("Accuracy");
		
		if (accuracy < 7) {
			formErrors[formErrors.length] = { message:"The address provided was not specific enough. Please enter the full address including street number", id: "addressError" };
		}
	}
	
	//check start date
	if (!/^20[0-9]{2}-[0-1][0-9]-[0-3][0-9]$/.test(f.elements["postStartDate"].options[f.elements["postStartDate"].selectedIndex].value)) {
		formErrors[formErrors.length] = { message:"Please select a start date.", id: "startDateError" };
	}
	
	//check end date
	if (!/^20[0-9]{2}-[0-1][0-9]-[0-3][0-9]$/.test(f.elements["postEndDate"].options[f.elements["postEndDate"].selectedIndex].value)) {
		formErrors[formErrors.length] = { message:"Please select an end date.", id: "endDateError" };
	}
	
	//check email address
	if (!/^[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/.test(f.postEmail.value)) {
		formErrors[formErrors.length] = { message:"Please enter a valid email address. Your information is kept confidential.", id: "emailError" };
	}
		
	//display errors, if any
	if (formErrors.length > 0) {
	
		//hide loading bar
		document.getElementById("loading").style.display = "none";
	
		for (var i = 0; i < formErrors.length; i++) {
			showError(formErrors[i].id, formErrors[i].message);
		}
		
	} else {
		//we should be good
		//get the geocoded address as returned by the server

		//strip html tags and new lines from fields (replace with br)
		var tags= /<\S[^><]*>/g;
		//var breaks= /[\n\r]/g;
		for (var i = 0;i < f.elements.length;i++) {
			if (f.elements[i].type == "text" || f.elements[i].type == "textarea") {
				f.elements[i].value = f.elements[i].value.replace(tags, "");
				//f.elements[i].value = f.elements[i].value.replace(breaks, "<br/>");
			}
		}
		
		if (!/.*addAddress.php$/.test(location.href) && !/.*addAddress.php$/.test(f.action)) {
			//safari comaptible method of extracting the code node value
			var addressBits = stringObj.split("<address>")[1];
			f.gAddress.value = addressBits.split("</address>")[0];
			
			var coordBits = stringObj.split("<coordinates>")[1];
			var coords = coordBits.split("</coordinates>")[0];
			f.lng.value = coords.split(",")[0];
			f.lat.value = coords.split(",")[1];
		} else {
			f.gAddress.value = f.postAddress.value;
		}

		f.submit();
	}

}

function deletePost() { //remove post from database
	if (confirm("Are you sure you want to delete your sale?")) {
		var f= document.forms["postForm"];
		document.location="/?do=delete&sid=" + f.elements["sid"].value + "&uid=" + f.elements["uid"].value;
	}
}

function showError(id,msg) {
	document.getElementById(id).innerHTML = msg;
	document.getElementById(id).style.display = "block";
}

function addEvent(obj, evType, fn, useCapture){
  if (obj.addEventListener){
    obj.addEventListener(evType, fn, useCapture);
    return true;
  } else if (obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
  } else {
    //alert("Handler could not be attached");
  }
}

function removeEvent(obj, evType, fn, useCapture){
  if (obj.removeEventListener){
    obj.removeEventListener(evType, fn, useCapture);
    return true;
  } else if (obj.detachEvent){
    var r = obj.detachEvent("on"+evType, fn);
    return r;
  } else {
    //alert("Handler could not be removed");
  }
}