var thisURL = '/';

// ------------------------------------------------------------------------------------
// This function gets called when the end-user clicks on some date.
function selected(cal, date) {
  cal.sel.value = date; // just update the date in the input field.
  if (cal.sel.id == "sel1" || cal.sel.id == "sel3")
    // if we add this call we close the calendar on single-click.
    // just to exemplify both cases, we are using this only for the 1st
    // and the 3rd field, while 2nd and 4th will still require double-click.
    cal.callCloseHandler();
}

// ------------------------------------------------------------------------------------
// And this gets called when the end-user clicks on the _selected_ date,
// or clicks on the "Close" button.  It just hides the calendar without
// destroying it.
function closeHandler(cal) {
  cal.hide();                        // hide the calendar
}

// ------------------------------------------------------------------------------------
// This function shows the calendar under the element having the given id.
// It takes care of catching "mousedown" signals on document and hiding the
// calendar if the click was outside.
function showCalendar(id, format) {
  var el = document.getElementById(id);
  if (calendar != null) {
    // we already have some calendar created
    calendar.hide();                 // so we hide it first.
  } else {
    // first-time call, create the calendar.
    var cal = new Calendar(false, null, selected, closeHandler);
    // uncomment the following line to hide the week numbers
    // cal.weekNumbers = false;
    calendar = cal;                  // remember it in the global var
    cal.setRange(1900, 2070);        // min/max year allowed.
    cal.create();
  }
  calendar.setDateFormat(format);    // set the specified date format
  calendar.parseDate(el.value);      // try to parse the text in field
  calendar.sel = el;                 // inform it what input field we use
  calendar.showAtElement(el);        // show the calendar below it

  return false;
}

var MINUTE = 60 * 1000;
var HOUR = 60 * MINUTE;
var DAY = 24 * HOUR;
var WEEK = 7 * DAY;

// ------------------------------------------------------------------------------------
// If this handler returns true then the "date" given as
// parameter will be disabled.  In this example we enable
// only days within a range of 10 days from the current
// date.
// You can use the functions date.getFullYear() -- returns the year
// as 4 digit number, date.getMonth() -- returns the month as 0..11,
// and date.getDate() -- returns the date of the month as 1..31, to
// make heavy calculations here.  However, beware that this function
// should be very fast, as it is called for each day in a month when
// the calendar is (re)constructed.
function isDisabled(date) {
  var today = new Date();
  return (Math.abs(date.getTime() - today.getTime()) / DAY) > 10;
}

// ------------------------------------------------------------------------------------
function flatSelected(cal, date) {
  var el = document.getElementById("preview");
  el.innerHTML = date;
}

// ------------------------------------------------------------------------------------
function showFlatCalendar() {
  var parent = document.getElementById("display");

  // construct a calendar giving only the "selected" handler.
  var cal = new Calendar(false, null, flatSelected);

  // hide week numbers
  cal.weekNumbers = false;

  // We want some dates to be disabled; see function isDisabled above
  cal.weekNumbers = false;

  // We want some dates to be disabled; see function isDisabled above
  cal.setDisabledHandler(isDisabled);
  cal.setDateFormat("DD, M d");

  // this call must be the last as it might use data initialized above; if
  // we specify a parent, as opposite to the "showCalendar" function above,
  // then we create a flat calendar -- not popup.  Hidden, though, but...
  cal.create(parent);

  // ... we can show it here.
  cal.show();
}


// ------------------------------------------------------------------------------------
function findZip(tzip,tcheck,showall) {
		
	var resultsdiv = document.getElementById('zipcodesearch');		
	var pickcity = document.getElementById('pickcity');		
	var pickcityimg = document.getElementById('pickcityimg');		
	
	if (tzip.length>3) {
		
		resultsdiv.innerHTML = "Checking...";
		
		var browser = navigator.appName; 
		if(browser == "Microsoft Internet Explorer"){
			var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}else{
			/* Create the object using other browser's method */
			var xmlhttp = new XMLHttpRequest();
		}
		
		var myURL = thisURL + 'system/ajaxgetzip.php?zip=' + tzip + '&check=' + tcheck + '&showall=' + showall;
				
		xmlhttp.open("GET", myURL, true);
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState == 4) { 
				var response = xmlhttp.responseText;
				
				if (response!=='') {				
					resultsdiv.innerHTML = response;
					pickcity.className = "Show";
					pickcityimg.className = "Show";
					
				} else {
					resultsdiv.innerHTML = 'No matching Zip Code found';
					pickcity.className = "Hide";
					pickcityimg.className = "Hide";
				}
				
				
			}
		}
			
		xmlhttp.send(null);
		
	} else {
		
		if (resultsdiv.innerHTML!='') {
			resultsdiv.innerHTML = '';	
			pickcity.className = "Hide";
		}
		
	}
			
}

// ------------------------------------------------------------------------------------
function checkAccount() {
	
	var f = document.forms['checkemail'];
	var email = f.login_username.value;
	var zip = f.zip.value;
	var spacenum = f.spacenum.value;
	var resultsdiv = document.getElementById('accountstatus');
	
	if (email!='') {
		
		resultsdiv.innerHTML = "Checking...";
		
		var browser = navigator.appName; 
		if(browser == "Microsoft Internet Explorer"){
			var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}else{
			/* Create the object using other browser's method */
			var xmlhttp = new XMLHttpRequest();
		}
		
		var myURL = thisURL + 'system/ajaxgetaccount.php?email=' + email + '&spacenum=' + spacenum + '&zip=' + zip;
						
		xmlhttp.open("GET", myURL, true);
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState == 4) { 
				var response = xmlhttp.responseText;
				resultsdiv.innerHTML = response;
				$('div.listing').curvy('10px');
			}
		}
			
		xmlhttp.send(null);
		
	} else {
		resultsdiv.innerHTML = '';
	}
	
	
}

// ------------------------------------------------------------------------------------
function sendForgottenEmail(email) {
	
	var resultsdiv = document.getElementById('forgotten');
	
	if (email!='') {
		
		var browser = navigator.appName; 
		if(browser == "Microsoft Internet Explorer"){
			var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}else{
			/* Create the object using other browser's method */
			var xmlhttp = new XMLHttpRequest();
		}
		
		var myURL = thisURL + 'system/ajaxsendemail.php?email=' + email;
				
		xmlhttp.open("GET", myURL, true);
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState == 4) { 
				var response = xmlhttp.responseText;
				resultsdiv.innerHTML = response;
			}
		}
			
		xmlhttp.send(null);
		
	} else {
		resultsdiv.innerHTML = '';
	}
	
	
}

// ------------------------------------------------------------------------------------
function showNearbyCities(miles, zipid, zip) {
	
	var resultsdiv = document.getElementById('nearbycities');
	var showhidespan = document.getElementById('nearbyvisible');
	
	if (miles!='' && zipid!='' && zip!='') {
		resultsdiv.innerHTML = "Loading...";
			
		var browser = navigator.appName; 
		if(browser == "Microsoft Internet Explorer"){
			var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}else{
			/* Create the object using other browser's method */
			var xmlhttp = new XMLHttpRequest();
		}
		
		var myURL = thisURL + 'system/ajaxgetcities.php?miles=' + miles + '&zipid=' + zipid + '&zip=' + zip;
				
		xmlhttp.open("GET", myURL, true);
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState == 4) { 
				var response = xmlhttp.responseText;
				resultsdiv.innerHTML = response;
				showhidespan.className = "Show";
			}
		}
			
		xmlhttp.send(null);
		
	} else {
		resultsdiv.innerHTML = '';
		showhidespan.className = "Hide";
	}
	
	
}

// ------------------------------------------------------------------------------------
function showHideDiv(tdiv) {
	
	var thediv = document.getElementById(tdiv);
	if (typeof(thediv)!='undefined') {
		
		if (thediv.className == "Hide") {
			thediv.className = "Show";
		} else {
			thediv.className = "Hide";
		}
		
	}
	
}

// ------------------------------------------------------------------------------------
function updateAmount(tmpformname) {
	
	var f = document.forms[tmpformname];
	
	if (typeof(f)!='undefined') {
		
		var discount = f.promotion_value.value;
		var paybox = document.getElementById('paybox');	
		var dispamount = document.getElementById('dispamount');	
		var thestring = f.product.options[f.product.selectedIndex].value;
		
		// Total the checkbox values...
		var checkarr;
		var itemtext;
		var price = 0;
		var extra = 0;
		
		for(i=0; i<document[tmpformname].elements.length; i++) {
			var el = document[tmpformname].elements[i];
			if(el.type=="checkbox") {								
				if (el.checked){
					
					// Explode ~
					itemtext = el.value;
					checkarr = itemtext.split("~");
					
					price = parseFloat(checkarr[2]);
										
					if (isNaN(price)) {
					} else {
						extra = extra + price;
					}
					
				}
			}
		}
	
		var prod_arr = thestring.split("~");
		var topspot = prod_arr[0];
		var numyears = prod_arr[1];
		var product = parseFloat(prod_arr[2]);
				
		if (numyears=="1") {
			product = product + extra;
		} else if (numyears=="2") {
			product = ((product*2)*0.9)+ (extra*2);
		} else if (numyears=="3") {
			product = ((product*3)*0.8)+ (extra*3);
		}
		
		// Add discount
		if (isNaN(discount)) {
		} else {
			product = product * ((100-discount)/100);
		}

		var finalamount = (Math.round(product*100)/100).toFixed(2);
				
		f.amount.value = finalamount;
		dispamount.innerHTML = '$' + finalamount;	
				
	}
	
}

// ------------------------------------------------------------------------------------
function sendMessage(formname, divname, srcid) {
	
	var resultsdiv = document.getElementById(divname);
	var f = document.forms[formname];
	var animated_panel = document.getElementById('click_' + srcid);
	var sendername = f.sm_name.value;
	var senderemail = f.sm_email.value;
	var sendermsg = f.sm_body.value;
	
	if (sendername!='' && senderemail!='' && sendermsg!='') {
		
		resultsdiv.innerHTML = 'Sending...';
		
		var browser = navigator.appName; 
		if(browser == "Microsoft Internet Explorer"){
			var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}else{
			/* Create the object using other browser's method */
			var xmlhttp = new XMLHttpRequest();
		}
		
		var myURL = thisURL + 'system/ajaxsendmessage.php?srcid=' + srcid + '&nm=' + sendername + '&em=' + senderemail + '&msg=' + escape(sendermsg);
			
		xmlhttp.open("GET", myURL, true);
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState == 4) { 
				var response = xmlhttp.responseText;
				resultsdiv.innerHTML = response;
				
				// Collapse main section
				animated_panel.click();
				
			}
		}
			
		xmlhttp.send(null);
		
	} else {
		alert('You must complete ALL required fields');
		f.sm_name.focus();
	}
	
	
}

// ------------------------------------------------------------------------------------
function setCountyCoverage() {
	
	var counties = document.forms['memberpay'].county;
	alert(counties.length);
				
}

// ------------------------------------------------------------------------------------
function checkPromotionalCode() {
	
	var f = document.forms['memberpay'];
	var code = f.promotion.value;
	var codedisp = document.getElementById('codedisp');
	
	if (code!='') {
		
		codedisp.innerHTML = 'Checking...';
		
		var browser = navigator.appName; 
		if(browser == "Microsoft Internet Explorer"){
			var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}else{
			/* Create the object using other browser's method */
			var xmlhttp = new XMLHttpRequest();
		}
		
		var myURL = '/system/ajaxgetpromotion.php?code=' + code;
											
		xmlhttp.open("GET", myURL, true);
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState == 4) { 				
				var response = xmlhttp.responseText;
				window.status = response;
				
				if (typeof(response) == 'undefined' || response=='') {
					f.promotion_value.value = '';
					f.promotion.value = '';
					f.promotion.focus();
					codedisp.innerHTML = 'Invalid Promotional Code';
					updateAmount('memberpay');
				
				} else {
					f.promotion_value.value = parseFloat(response);
					codedisp.innerHTML = 'Code accepted - ' + response + '% off!';
					updateAmount('memberpay');
				} 
				
			}
		}
		
		xmlhttp.send(null);
		
	} else {
		codedisp.innerHTML = '';
	}
	
}

// ------------------------------------------------------------------------------------
function imposeMaxLength(Object, MaxLen) {
  return (Object.value.length <= MaxLen);
}

// ------------------------------------------------------------------------------------
function sendSMSTest() {
	
	var f = document.forms['mylisting'];
	var cell = f.cell.value;
	
	// Clean up phone
	var tcell = cell;
	tcell = tcell.replace('(','');
	tcell = tcell.replace(')','');
	tcell = tcell.replace('.','');
	tcell = tcell.replace('-','');
	tcell = tcell.replace(' ','');
	
	var carrierid = f.carrierid.selectedIndex;
	var confmsg = 'This action will send a test text message to the following number:\n\n' + cell + '\n\nPress OK to proceed';
	
	if (carrierid>0 && tcell.length==10) {
		
		if (confirm(confmsg)) {
			
			var browser = navigator.appName; 
			if(browser == "Microsoft Internet Explorer"){
				var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			}else{
				/* Create the object using other browser's method */
				var xmlhttp = new XMLHttpRequest();
			}
			
			var myURL = thisURL + 'system/ajaxsendtestsms.php?phone=' + tcell + '&carrierid=' + carrierid;
								
			xmlhttp.open("GET", myURL, true);
			xmlhttp.onreadystatechange=function() {
				if (xmlhttp.readyState == 4) { 
					var response = xmlhttp.responseText;
										
					if (response=='1') {				
						alert('Test text message sent to ' + cell + '\n\nIf you do not receive the test message within 5 minutes please contact us');
					} else {
						alert('Oops - something went wrong - please check your phone number and carrier');
					}
					
					
				}
			}
				
			xmlhttp.send(null);
			
		}
	
	} else {
		alert('You must complete your 10-digit Phone number (numbers only) and select your Carrier.');
		f.phone.focus();
	}
	
}

// ------------------------------------------------------------------------------------
function orderAppraisal(unid) {
	
	if (isNaN(unid)) {
		alert('Oops.  There has been a problem creating an order for this Appraiser');
		
	} else {
		var myURL = thisURL + 'order.php?unid=' + unid + '&new=1';
		document.location.href = myURL;
		
	}
	
}

// ------------------------------------------------------------------------------------
function saveRating(apporderid) {
	
	var f = document.forms['mylisting'];
	var ratingspan = document.getElementById('rateappraiser');
	var rating_comments = f.rating_comments.value;
	
	var myOption = -1;
	for (i=f.myrating.length-1; i > -1; i--) {
		if (f.myrating[i].checked) {
			myOption = i; 
			i = -1;
		}
	}
	
	if (myOption == -1) {
		alert("You must select a rating");
		return false;
		
	} else {
		
		var rating = f.myrating[myOption].value;
		
		if (rating == '1' && rating_comments.length==0) {
			alert('You must enter a reason for this negative rating');
			f.rating_comments.focus();
			return false;
			
		} else {
			
			ratingspan.innerHTML = '<center>Saving...</center>';
			
			// Passed validation - proceed
			var browser = navigator.appName; 
			if(browser == "Microsoft Internet Explorer"){
				var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			}else{
				/* Create the object using other browser's method */
				var xmlhttp = new XMLHttpRequest();
			}
			
			var myURL = thisURL + 'system/ajaxsetrating.php?apporderid=' + apporderid + '&rating=' + rating + '&comments=' + escape(rating_comments);
					
			xmlhttp.open("GET", myURL, true);
			xmlhttp.onreadystatechange=function() {
				if (xmlhttp.readyState == 4) { 
					var response = xmlhttp.responseText;
					ratingspan.innerHTML = '<center>Rating saved - thank you!</center>';
				}
			}
				
			xmlhttp.send(null);
				
		}
		
	}

}

// ------------------------------------------------------------------------------------
function duplicateAddress() {
	
	var f = document.forms['mylisting'];
	
	if (f.duplicate.checked) {
		f.p_address.value = f.b_address.value;
		f.p_city.value = f.b_city.value;
		f.p_zip.value = f.b_zip.value;
		
	} else {
		f.p_address.value = '';
		f.p_city.value = '';
		f.p_zip.value = '';
		
	}
	
}

// ------------------------------------------------------------------------------------
function focusZipCode() {
	
	var zipcodebox = document.getElementById('mainzipcode');
	//if (typeof(zipcodebox)!='undefined') {
	//	zipcodebox.focus();
	//}
	
}

// ------------------------------------------------------------------------------------
function removeListing(unid) {
	
	if (confirm('Are you sure you wish to delete this listing?  This action cannot be undone')) {
		
			var browser = navigator.appName; 
			if(browser == "Microsoft Internet Explorer"){
				var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			}else{
				/* Create the object using other browser's method */
				var xmlhttp = new XMLHttpRequest();
			}
			
			var myURL = thisURL + 'system/ajaxremovelisting.php?unid=' + unid;
					
			xmlhttp.open("GET", myURL, true);
			xmlhttp.onreadystatechange=function() {
				if (xmlhttp.readyState == 4) { 
					var response = xmlhttp.responseText;
					document.location.href = '/myproperties.php';
				}
			}
				
			xmlhttp.send(null);
		
	}
	
}

// ------------------------------------------------------------------------------------
function clickclear(thisfield, defaulttext) {
	if (thisfield.value == defaulttext) {
		thisfield.value = "";
	}
}

// ------------------------------------------------------------------------------------
function clickrecall(thisfield, defaulttext) {
	if (thisfield.value == "") {
		thisfield.value = defaulttext;
	}
}