var xmlhttp=false;

if(!xmlhttp && typeof XMLHttpRequest!='undefined') {
	try {
		xmlhttp = new XMLHttpRequest();
	}
	catch (e) {
		xmlhttp=false;
	}
}
if (!xmlhttp && window.createRequest) {
	try {
		xmlhttp = window.createRequest();
	}
	catch(e){
		xmlhttp=false;
	}
}


function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function popUpWindow(URLStr, left, top, width, height){
	popUpWin = open(URLStr, 'popUpWin', 'toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,copyhistory=yes,width='+width+',height='+height+',left='+left+', top='+top+',screenX='+left+',screenY='+top+'');
	popUpWin.focus();
}


//either shows or hides an element based on its current status
function showHideElement(elementId){
	if(document.getElementById(elementId).style.display=='none'){
		document.getElementById(elementId).style.display = '';
	}
	else{
		document.getElementById(elementId).style.display = 'none';
	}
}

function hideElement(elementId){
	if(document.getElementById(elementId)){
		document.getElementById(elementId).style.display = 'none';
	}
}

function showElement(elementId){
	if(document.getElementById(elementId)){
		document.getElementById(elementId).style.display = '';
	}
}

function replaceBadCharacters(string) {
    for (var i=0, output='', valid="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ _.-'=*&^%][!@$/+,}{)(#:;\"'=*\\"; i<string.length; i++)
       if (valid.indexOf(string.charAt(i)) != -1)
          output += string.charAt(i)
    return output;
}

function validateString(element){
      
    stringType = element.substr(0, 4);
	if(!document.getElementById(element)){
		alert(element + ' does not have a valid ID!');
		return false
	}
    stringToTest = document.getElementById(element).value;
	re = /^$/;
	canBeEmpty = element.substr(4,1);
	if(canBeEmpty=='t'){
		canBeEmpty = true;
	}
	else if(canBeEmpty=='f'){
		canBeEmpty = false;
	}
	if(canBeEmpty==true && stringToTest==''){
		return true;
	}
    
	
	
    	if(stringType=='phon'){re = /^[a-zA-Z0-9\ \(\)\-\+]{4,100}$/;}
    
    	if(stringType=='emal'){re = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,6})+$/;}
    
    	if(stringType=='pass'){re = /^[a-zA-Z0-9\?\.\,\/\!\@\#\$\%\^\&\*\(\)\ \:\;\=\+\_\-\]\[\{\}]{6,32}$/;}
    
    	if(stringType=='numb'){re = /^\-{0,1}([0-9\,]+)$/;}
    
    	if(stringType=='zipc'){re = /^[a-zA-Z0-9\-\ ]{5,15}$/;}
    
    	if(stringType=='ccrd'){re = /^[0-9]{13,16}$/;}
    
    	if(stringType=='gtxt'){re = /^[a-zA-Z0-9\?\.\,\/\!\@\#\$\%\^\&\*\(\)\ \r\n\'\"\:\;\=\+\_\-\]\[\{\}\~]+$/;}
    
    	if(stringType=='user'){re = /^[a-zA-Z0-9\@\.]{4,255}$/;}
    
    	if(stringType=='date'){re = /^([0-9]){2,2}\/([0-9]){2,2}\/([0-9]){4,4}$/;}
    
    	if(stringType=='flot'){re = /^\-{0,1}[0-9]{1,6}[\.]{0,1}[0-9]{0,2}$/;}
    
    	if(stringType=='name'){re = /^([a-zA-Z0-9\ \-\,\.\(\)\/\:\\\'\&]){1,64}$/;}
    
    	if(stringType=='link'){re = /^(?:(?:ftp|https?):\/\/){0,1}(?:[a-z0-9](?:[-a-z0-9]*[a-z0-9])?\.)+(?:com|edu|biz|org|gov|int|info|mil|net|name|museum|coop|aero|mobi|tv|us|[a-z][a-z])\b(?:\d+)?(?:\/[^;"'<>()\[\]{}\s\x7f-\xff]*(?:[.,?]+[^;"'<>()\[\]{}\s\x7f-\xff]+)*)?$/;}
    

	goodString = false;

	goodString = re.test(stringToTest);
	if(goodString){
		return true;
	}
	else{
		return false;
	}
}

function validateForm(formName){
      
      var obj = document.forms[formName]
      deleting = false;
      delre = /delete/;  //regular expression for delete check box
      	// Create new "processing form..." obejct
	  
	  startPause(500);
	  
      for (i=0; obj.elements[i]; i++) {
            
            currentElement = obj.elements[i].name;
            currentValue = obj.elements[i].value;
            isValid = true;
            
            if(delre.test(currentElement)){
                  if(obj.elements[i].checked==true){
                        deleting = true;
                  }
            }
            hideAlert = false;
            if(currentElement.substr(4,2)=='t-' || currentElement.substr(4,2)=='f-'){
                  stringType = currentElement.substr(0,4);
                  canBeEmpty = currentElement.substr(4,1);
                  fieldPrettyName = currentElement.substr(6,999);
                  if(canBeEmpty=='t'){
                        canBeEmpty = true;
                  }
                  else if(canBeEmpty=='f'){
                        canBeEmpty = false;
                  }
                  if(stringType=='blnk' && (canBeEmpty==true || document.getElementById(currentElement).value!='')){
                  	isValid = true;
                  }
				  else if(stringType=='blnk' && canBeEmpty==false){
				  	isValid = false;
				  }
                  else{
                  	isValid = validateString(currentElement);
                  }
            }
            
			if(currentElement == 'emalf-email' && document.getElementById('emalf-email_confirm')){
				if(document.getElementById('emalf-email').value != document.getElementById('emalf-email_confirm').value){
					alert('Your email addresses do not match.');
					isValid = false;
                    hideAlert = true;
				}
			}
			
            if(!isValid){
				
				
				canBeEmptyWarning = 'This field can be blank.';
				if(canBeEmpty==false){
					canBeEmptyWarning = 'This field may NOT be blank.';
				}
				obj.elements[i].focus();
				obj.elements[i].className='formError';
				replaceChars = false;
				
				if(stringType=='gtxt' && (canBeEmpty==false && currentValue!='')){
					replaceChars = confirm('The highlighted field (red) contains invalid content.\nWould you like to automatically fix the invalid content?');
					hideAlert = true;
				}

				if(replaceChars==true){
					obj.elements[i].value = replaceBadCharacters(currentValue);
				}
				else if(hideAlert==false){
					alert('The highlighted field (red) contains invalid content.\n' + validateDescription(stringType) + '\n' + canBeEmptyWarning);
				}
				return false;
				break;
            }
            else{
                  obj.elements[i].className='';
            }
      }
      
      if(deleting==true){
            return confirm('You have objects selected for deletion.\n This cannot be undone!\n Are you sure you wish to continue?');
      }
      return true;
}

function validateDescription(stringType){
	
    if(stringType=='phon'){return "A phone number can contain numbers, dashes, spaces, and paraentheses, and must be 4-100 characters long";}
    if(stringType=='emal'){return "An email address, must contain the @ symobol and a valid domain name; like joe@example.com.";}
    if(stringType=='pass'){return "A password between 6 and 32 characters long and can contain letters, numbers, and most special characters. e.g. PassWord1";}
    if(stringType=='numb'){return "A whole number containing no decimals, or spaces.  Like 23, -158, or 79,500.";}
    if(stringType=='zipc'){return "A zip code can contain letters, numbers, and hyphens only, and must be 5-15 characters long.";}
    if(stringType=='ccrd'){return "Must be a valid credit card number.";}
    if(stringType=='gtxt'){return "General text, can contain almost every character with a few exceptions like < and >.";}
    if(stringType=='user'){return "A username, between 4 and 32 characters long and can consist of numbers and letters; like Matt";}
    if(stringType=='date'){return "A date must be in the format mm/dd/yyyy.  For example 03/05/1979.";}
    if(stringType=='flot'){return "A floating point number can be a whole number or a decimal, like 6 or 5.34, that contains no commas.";}
    if(stringType=='name'){return "A person's name, can contain any combination of letters, spaces, dashes, and can be up to 64 characters long. Like Anne, or Smith.";}
    if(stringType=='link'){return "A full and valid link, including a valid protocol.  e.g. http://www.example.com/page.html or ftp://example.com/foldername/";}
	return '';
}

function openWindow(pageLoc,pageName,winWidth,winHeight) {
	window.open(pageLoc,pageName,'top=0,left=0,width=' + winWidth + ',height=' + winHeight + ',scrollbars=yes,menubar=no,resizable=yes');
}

function formatPhoneNumber(elementID){
	if(document.getElementById(elementID)){
		number_final = '';
		number = document.getElementById(elementID).value;
		for(i=0; i<number.length; i++){
			temp_number = number.substr(i, 1);
			if(isNumber(temp_number)){
				number_final = number_final + temp_number;
			}
		}
		if(number_final.length>7){
			document.getElementById(elementID).value = '(' + number_final.substr(0, 3) + ') ' + number_final.substr(3, 3) + '-' + number_final.substr(6, 4);
		}
	}
}

function roundFloat(floatNum,dec){
	floatNum = parseFloat(floatNum);
    return floatNum.toFixed(dec);
}

function isNumber(number){
    re = /^[0-9\.]+$/;
    return re.test(number);
}

function floor(number){
  return Math.floor(number*Math.pow(10,2))/Math.pow(10,2);
}

function dosum(){
	var mi = document.getElementById('ir').value / 1200;
	var base = 1;
	var mbase = 1 + mi;
	for (i=0; i<document.getElementById('yr').value * 12; i++){
		base = base * mbase
	}
	document.getElementById('pi').value = floor(document.getElementById('la').value * mi / ( 1 - (1/base)))
	document.getElementById('mt').value = floor(document.getElementById('at').value / 12)
	document.getElementById('mi').value = floor(document.getElementById('ai').value / 12)
	var dasum = document.getElementById('la').value * mi / ( 1 - (1/base)) +
	document.getElementById('at').value / 12 + document.getElementById('ai').value / 12;
	document.getElementById('mp').value = floor(dasum);
}

function byOwnerCalendar(listingID){
	popUpWindow('http://www.adkbyowner.com/availability.cfm?i='+listingID, 10, 10, 500, 600);
}



function startPause(pauseLength) {
	timer = setTimeout("endPause()", pauseLength);
	return false;
}

function endPause() {
	return false;
}

var regionName = '';
var regionNameTries = 0;
var lastPropertyTown = '';



function updateRegionDisplayContent(editingListing)
{
	
	if(document.getElementById('blnkt-city').value!=''){
    
    	//get city name from value (city_name|ID
        var pipeIndex = document.getElementById('blnkt-city').value.lastIndexOf("|");
		var theCityName = document.getElementById('blnkt-city').value.substring(0,pipeIndex);
        var theCityID = document.getElementById('blnkt-city').value.substring(pipeIndex+1);
    	//alert(theCityID);
        

    	if(editingListing)
        {
        	
    		oktoChange = alert('NOTICE: You just changed your property\'s location to the town of "'+theCityName+'".\nThis may change the region your property is located under.');
        }
        lastPropertyTown = theCityName;
	}
	
    regionName = getRegionNameFromCityID(theCityID);
   
	setTimeout("waitUpdateRegionDisplayContent()", 1000);
}

function waitUpdateRegionDisplayContent()
{
	
	if(regionName=='' && regionNameTries<10){
		setTimeout("waitUpdateRegionDisplayContent()", 1000);
		regionNameTries++;
	}
    
    //reset counter
    regionNameTries = 0;
    
	if(regionName=='' || document.getElementById('blnkt-city').value==''){
		newContent = '';
	}
	else{
    	var pipeIndex = document.getElementById('blnkt-city').value.lastIndexOf("|");
		var theCityName = document.getElementById('blnkt-city').value.substring(0,pipeIndex);
        
        
        
		newContent = 'You selected the town of "' + theCityName + '" which is part of the "' + regionName + '"';
	}
	changeHTMLContent('regionDisplayContent', newContent);
	return true;
}


function changeHTMLContent(ElementId,newValue){
    //document.getElementById(ElementId).replaceChild(document.createTextNode(newValue), document.getElementById(ElementId).childNodes[0]);
    document.getElementById(ElementId).innerHTML = newValue;
}

function getRegionNameFromCityName(cityName){
	regionName = '';
	xmlhttp.open("GET", 'http://www.adkbyowner.com/owners/includes/ajax-getRegionNameFromCity.cfm?city='+cityName,true);
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4)	regionName = (xmlhttp.responseText);
	}
	xmlhttp.send(null)
	return regionName;
}

function getRegionNameFromCityID(cityID)
{
	
	
    xmlhttp.open("GET", 'http://www.adkbyowner.com/owners/includes/ajax-getRegionNameFromCityID.cfm?cityID='+cityID,true);
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4)
        {
        	regionName = xmlhttp.responseText;
            return regionName;
        }
	}
	xmlhttp.send(null);
	
}

// enables the blink tag for browsers that do not support it.
function blinkIt() {
	if (!document.all) return;
	else {
		for(i=0;i<document.all.tags('blink').length;i++){
			s=document.all.tags('blink')[i];
			s.style.visibility=(s.style.visibility=='visible')?'hidden':'visible';
		}
	}
}
setInterval('blinkIt()',500);

function openCalendarDayToggle(listingID, dayToOpen, monthToOpen, yearToOpen, dayElementToChange){
	newClassName = '';
	randNumber = Math.floor(Math.random()*99999999);
	xmlhttp.open("GET", 'http://www.adkbyowner.com/owners/modules/hide-Availability.cfm?i='+listingID+'&dayToggle='+dayToOpen+'&dayMonth='+monthToOpen+'&monthYear='+yearToOpen+'&bareMode=true&rand='+randNumber,true);
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4){
			if(trim(xmlhttp.responseText)!=''){
				newClassName = trim(xmlhttp.responseText);
				document.getElementById(dayElementToChange).className = newClassName;
        return 0;
			}
		}
	}
	xmlhttp.send(null);
	return 0;
}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s*/, "").replace(/\s*$/, "");
}






function updateYear(e) {
	year = e.options[e.selectedIndex].innerHTML;
	document.getElementById('arrivalYear').value = year.substring(0, 4);
}




function getEndDateFromStartDate(d)
{
	if(!Date.parse(d)) return false;

	try{
    
	var sd = new Date(d.substr(6),d.substr(0,2)-1,d.substr(3,2),0,0,0,0);
    //add the proper number of milliseconds (based on the application.end_date_offset number of days)
    //num ms per day is (24 * 60 * 60 * 1000) = 86400000 ms per day
    
    var ms_per_day = (24 * 60 * 60 * 1000);
    var end_date_ms_offset = (ms_per_day * 2);
    
    sd.setTime(sd.getTime()+end_date_ms_offset);

    var new_start_day = sd.getDate();
    var new_start_mon = sd.getMonth()+1;
	if(new_start_day < 10) new_start_day = "0"+new_start_day;
    if(new_start_mon < 10) new_start_mon = "0"+new_start_mon;

    return (new_start_mon)+"/"+new_start_day+"/"+sd.getFullYear();
   
    }
    catch(e)
    {	
    	return false;
    }
}

